小编典典

React的getDefaultProps()内部的this.props吗?

reactjs

我正在尝试添加一个依赖于其他道具的道具,这些道具基本上将由组件的所有者组件传递。

所以我做了:

propTypes: {
  user: React.PropTypes.object,
  comment: React.PropTypes.object
},

getDefaultProps: function() {
  return {
    admire: new Admire({
              user: this.props.user, 
              comment:this.props.comment
            })
  };
}

但这似乎是道具usercommentgetDefaultProps通话时无法访问。

有什么方法可以定义默认的道具,该默认道具依赖于将从所有者组件传递的其他道具?


阅读 258

收藏
2020-07-22

共1个答案

小编典典

getDefaultProps在创建任何实例之前被调用,因此不能依赖this.props。这是为了在所有者未通过默认道具的情况下获取默认道具。

另一种解决方案是使用,getInitialState因为这将使您可以访问this.props.userthis.props.comment

2020-07-22