首页 > 其他 > 详细

[React] Use React.cloneElement to Extend Functionality of Children Components

时间:2017-02-06 21:01:38      阅读:180      评论:0      收藏:0      [点我收藏+]

We can utilize React.cloneElement in order to create new components with extended data or functionality.

 

class App extends React.Component {
  render(){
    return (
      <Buttons>
        <button value="A">A</button>
        <button value="B">B</button>
        <button value="C">C</button>
      </Buttons>
    )
  }
}


class Buttons extends React.Component {
  constructor(){
    super();
    this.state = {selected: ‘None‘}
  }
  selectItem(selected){
    this.setState({selected})
  }
  render(){
      let fn = child =>
        React.cloneElement(child, {
          onClick:this.selectItem.bind(this, child.props.value)
        })
      let items = React.Children.map(this.props.children, fn);
      return (
        <div>
          <h2>You have selected: {this.state.selected}</h2>
          {items}
        </div>
      )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById(‘root‘)
);

 

We render {items} below h2 tag, and for each button element in Buttons, we are going to extend the element by adding a ‘onClick‘ method to it.

[React] Use React.cloneElement to Extend Functionality of Children Components

原文:http://www.cnblogs.com/Answer1215/p/6371707.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!