繁体   English   中英

在 React 中传递 props 并在另一个组件中对其进行子串

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM