javascript - 在 React 中传递 Props 并将其子串到另一个组件中

标签 javascript reactjs function substring react-props

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

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

相关文章:

JavaScript 压缩/解压缩。如何使用数组减少

javascript - tinymce 不显示离开页面的警报

javascript - 如何在网络中检测用户操作系统/浏览器信息(使用 php、js、html)?

javascript - 如何解决 Eslint - Module.createRequire 不是函数错误?

javascript - Material UI 图标无法正确渲染

java - fn : functions in XPathExpressions cause Exceptions in JDK1. 6

php - PHP函数中的错误处理而不会崩溃

c++ - 如何使这个函数递归

javascript - 如何不通过引用分配

reactjs - Yup 中的自定义验证方法抛出 TypeScript 错误