我正在尝试设计一个关于个人资料的文本,该文本可以根据其长度选择阅读更多/阅读更少, 从家里调用函数为
<AboutText text={aboutData}/>
AboutText 组件
import React from 'react';
import './profile.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import 'font-awesome/css/font-awesome.min.css';
class AboutText extends React.Component {
state = {
showAll : false
}
showMore = () => {this.setState({showAll : true})};
showLess = () => {this.setState({showAll : false})};
render(){
const {text} = this.props;
if(text.length <= 150 ){
return(
<p className="about p-3 mt-2 text-dark">{text}</p>
)
}
if(this.state.showAll) {
return (<React.Fragment>
<p className="about p-3 mt-2 text-dark">{text}
<a className="ml-3" onClick={this.showLess}>Read less</a></p>
</React.Fragment>
) }
const toShow = text.substring(0,150)+".....";
return <div>
<p className="about p-3 mt-2 text-dark">{toShow}
<a className="ml-3" onClick={this.showMore}>Read more</a></p>
</div>
} }
export default AboutText;
当我将直接数据作为 Prop 传递时,它工作正常
<AboutText text="some long string"/>
但在将状态作为属性传递时不起作用..它显示各种错误,例如文本未定义
子字符串不是函数..提前感谢
最佳答案
如果你想使用State
中的text
,你需要在构造函数中初始化它,如下所示:
constructor(props) {
super(props);
this.state = {
showAll : false,
text: props.text
}
}
现在,您可以在 render
中使用 State
中的 text
,如下所示:
render() {
const { text } = this.state;
...
}
关于javascript - 在 React 中传递 Props 并将其子串到另一个组件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60466711/