【发布时间】:2015-11-20 20:22:49
【问题描述】:
我想知道是否有比使用 if 语句更好的方法来有条件地传递道具。
例如,现在我有:
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 中的一种 inline-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 仍然拉prop 的值来自Child 自己的getDefaultProps()。
【问题讨论】:
-
你能把
Child的代码也包括进来吗?另外,你的意思是说<Child editableOpts={this.props.editableOpts} />而不是<Child editable={this.props.editableOpts} />? -
@JimSkerritt 我没有混淆道具,尽管我知道它看起来是那样的。我正在尝试使用
react-bootstrap-table,这就是他们使用的格式。我不确定Child代码对我所要求的内容是否真的很重要,这就是我没有包含它的原因。我真的只是在寻找一种方法来选择性地将道具传递或不传递给Child,这不需要在Parent的if 语句中包含大量类似的代码。
标签: javascript reactjs inline