React:内联有条件地将 prop 传递给组件

新手上路,请多包涵

我想知道是否有比使用 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 许可协议

阅读 377
2 个回答

你很接近你的想法。事实证明,为道具传递 undefined 与根本不包含它是一样的,这仍然会触发默认道具值。所以你可以这样做:

 var parent = React.createClass({
  propTypes: {
    editable: React.PropTypes.bool.isRequired,
    editableOpts: React.PropTypes.shape({...})
  },
  render: function() {
    return <Child
      editable={this.props.editable ?
                  this.props.editableOpts :
                  undefined}
    />;
  }
});

原文由 Jim Skerritt 发布,翻译遵循 CC BY-SA 3.0 许可协议

将扩展运算符添加到 this.props.editable

 <Child {...(this.props.editable ? {editable: this.props.editableOpts} : {})} >

应该管用。

原文由 Jamal Hussain 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题