小编典典

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

reactjs

我想知道是否有比使用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中的一种inif-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()


阅读 272

收藏
2020-07-22

共1个答案

小编典典

您的想法很贴切。事实证明,传递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}
    />;
  }
});
2020-07-22