相关疑难解决方法(0)

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

我想知道是否有一种更好的方式来有条件地传递道具而不是使用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 />
      );
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

有没有办法在没有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} 
      />
    );
  }
});
Run Code Online (Sandbox Code Playgroud)

总结:我正试图找到一种方法来定义一个道具Child,但是传递一个值(或做一些其他的),这样Child …

javascript inline reactjs

59
推荐指数
6
解决办法
4万
查看次数

标签 统计

inline ×1

javascript ×1

reactjs ×1