在 React 中传递 Props 并在另一个组件中将其子字符串化

Passing Props in React And Substring It In Another Component

我正在尝试设计个人资料的关于文本,可以根据其长度选择阅读更多/阅读更少, 从家里调用函数

<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"/>

但在将状态作为 prop 传递时不起作用。它显示各种错误,例如 text is undefined substring is not a function ..提前致谢

不够清楚!但总的来说,在传递之前尝试声明 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;
   ...
}