简体   繁体   English

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

[英]Passing Props in React And Substring It In Another Component

I am trying to design an about text of a profile that will have a option to read more / read less according to its length, calling function from home as我正在尝试设计一个关于个人资料的文本,可以选择根据其长度阅读更多/更少阅读,从家里调用函数

<AboutText text={aboutData}/>

AboutText Component关于文本组件

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;

when i am passing direct data as prop it works fine当我将直接数据作为道具传递时,它工作正常

     <AboutText text="some long string"/>

but not working when passing state as prop ..it shows various errors such as text is undefined substring is not a function ..thanks in advance但在将状态作为道具传递时不起作用..它显示了各种错误,例如text is undefined子字符串不是函数..提前致谢

it's not clear enough !还不够清楚! but over all try declaration React.Component<aboutData:String> before passing it.但在传递之前,请尝试声明React.Component<aboutData:String> and do :并做:

constractor(){
super(props)
....
}

If you want to use text from State , you need to initialise it in constructor as shown below:如果要使用State text ,则需要在构造函数中初始化它,如下所示:

constructor(props) {
    super(props);
    this.state = {
        showAll : false,
        text: props.text
      }
}

Now, you can use text from State in render as shown below:现在,您可以在render使用State中的text ,如下所示:

render() {
   const { text } = this.state;
   ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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