[英]Passing Props in React And Substring It In Another Component
我正在嘗試設計一個關於個人資料的文本,可以選擇根據其長度閱讀更多/更少閱讀,從家里調用函數
<AboutText text={aboutData}/>
關於文本組件
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;
當我將直接數據作為道具傳遞時,它工作正常
<AboutText text="some long string"/>
但在將狀態作為道具傳遞時不起作用..它顯示了各種錯誤,例如text is undefined
子字符串不是函數..提前致謝
還不夠清楚! 但在傳遞之前,請嘗試聲明React.Component<aboutData:String>
。 並做:
constractor(){
super(props)
....
}
如果要使用State
text
,則需要在構造函數中初始化它,如下所示:
constructor(props) {
super(props);
this.state = {
showAll : false,
text: props.text
}
}
現在,您可以在render
使用State
中的text
,如下所示:
render() {
const { text } = this.state;
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.