我正在尝试添加一个依赖于其他道具的道具,这些道具基本上将由组件的所有者组件传递。
所以我做了:
propTypes: { user: React.PropTypes.object, comment: React.PropTypes.object }, getDefaultProps: function() { return { admire: new Admire({ user: this.props.user, comment:this.props.comment }) }; }
但这似乎是道具user,comment在getDefaultProps通话时无法访问。
user
comment
getDefaultProps
有什么方法可以定义默认的道具,该默认道具依赖于将从所有者组件传递的其他道具?
getDefaultProps在创建任何实例之前被调用,因此不能依赖this.props。这是为了在所有者未通过默认道具的情况下获取默认道具。
this.props
另一种解决方案是使用,getInitialState因为这将使您可以访问this.props.user和this.props.comment。
getInitialState
this.props.user
this.props.comment