LoginSignup
8
8

More than 5 years have passed since last update.

Reactで子要素を渡せるコンポーネントを作りたい

Last updated at Posted at 2015-02-14

Reactでこんな感じのやつを作りたい。

jsx
<ButtonGroup selected={this.state.selected} onSelect={this.onSelect}>
  <Button>foo</Button>
  <Button>bar</Button>
  <Button>baz</Button>
</ButtonGroup>

Screen Shot 2015-02-14 at 11.01.10 PM.png

ButtonにButtonGroupからpropsを指定するためのいい方法がイマイチわからないんだけど、React Bootstrapとかのコード読んでるとcloneWithPropsで複製してpropsを渡してるみたいだった。

こんな感じになった。

var ButtonGroup = React.createClass({
  onSelect: function(index) {
    this.props.onSelect(index);
  },
  render: function() {
    var children = this.props.children.map(function(child, i) {
      return React.addons.cloneWithProps(child, {
        key: i,
        index: i,
        onClick: this.onSelect,
        selected: +this.props.selected === i,
      });
    }, this);

    return <div className="btnGroup">{children}</div>;
  }
});

var Button = React.createClass({
  onClick: function() {
    this.props.onClick(this.props.index);
  },
  render: function() {
    var cls = this.props.selected ? 'btn selected' : 'btn';
    return <span className={cls} onClick={this.onClick}>{this.props.children}</span>;
  }
});

でも @koba04 さんの記事にcloneWithPropsはあんまり使いたい場面が思い浮かばないって書いてあるのでもっといい方法があるのではと思っている。

8
8
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8