【问题标题】:es6 react getting props in child componentes6 反应在子组件中获取道具
【发布时间】:2016-08-20 13:10:08
【问题描述】:

我一直在将我的一个应用程序迁移到 node/react 上的 ES6,我有一个关于如何将道具传递给孩子的问题。我阅读了一堆帖子,其中一些解决了这个问题,而另一些则没有。基本上,我目前看到的是这样的:

export default class SomeComponent extends React.Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <div>
               {this.props.text} <<< Props used here
            </div>
        );
    }
}

但我已经能够让我的组件使用以下内容:

export default class SomeComponent extends React.Component {
    constructor() {
        super(); <<< notice no props in parentheses 
    }
    render() {
        return (
            <div>
               {this.props.text} <<< Props used here
            </div>
        );
    }
}

是否有理由为我的构造函数和超级调用传递括号中的道具?或者我可以保留我的代码吗

【问题讨论】:

    标签: reactjs ecmascript-6


    【解决方案1】:

    除非你想在构造函数中使用 this.props,否则你不需要将 props 传递给 super。

    https://stackoverflow.com/a/34995257/3238350

    【讨论】:

      【解决方案2】:

      你必须传递 props,因为你是从 React.Component 扩展而来的,否则你将无法在构造函数中访问 this.props。

      这是某种构图模式。

      【讨论】:

      • 但它确实有效,我现在正在运行它并且它正在工作
      • 好吧,我想这不是必需的,除非您需要在构造函数中使用 this.props,例如设置初始状态
      • 如果你不做任何事情,你根本不必使用构造函数。即使你想设置初始状态,如果你使用componentWillMount() { this.setState({}) }
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-03
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      • 2019-05-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多