1. ホーム
  2. javascript

[解決済み] React: インラインでpropをコンポーネントに条件付きで渡す

2022-08-19 18:13:27

質問

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 />
      );
    }
  }
});

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 はまだそのプロップの値を Child にある getDefaultProps() .

どのように解決するのですか?

あなたのアイデアに近いものでした。それは 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}
    />;
  }
});