我想知道是否有比使用 if 语句更好的有条件地传递 prop 的方法。
例如,现在我有:
var parent = React.createClass({
propTypes: {
editable: React.PropTypes.bool.isRequired,
editableOpts: React.PropTypes.shape({...})
},
render: function() {
if(this.props.editable) {
return (
<Child editable={this.props.editableOpts} />
);
} else {
// In this case, Child will use the editableOpts from its own getDefaultProps()
return (
<Child />
);
}
}
});
有没有办法不用 if 语句来写这个?我正在考虑 JSX 中的一种内联 if 语句:
var parent = React.createClass({
propTypes: {
editable: React.PropTypes.bool.isRequired,
editableOpts: React.PropTypes.shape({...})
},
render: function() {
return (
<Child
{this.props.editable ? editable={this.props.editableOpts} : null}
/>
);
}
});
_总结_:我试图找到一种方法来为 Child
定义一个道具,但传递一个值(或做其他事情)使得 Child
仍然拉动那个道具的价值来自 Child
自己的 getDefaultProps()
。
原文由 Matthew Herbst 发布,翻译遵循 CC BY-SA 4.0 许可协议
你很接近你的想法。事实证明,为道具传递
undefined
与根本不包含它是一样的,这仍然会触发默认道具值。所以你可以这样做: