zoukankan      html  css  js  c++  java
  • [React] Use React.cloneElement to Extend Functionality of Children Components

    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.

  • 相关阅读:
    回老家
    防疫针
    平安夜
    虎威威
    圣诞联欢会
    小老虎飞船
    电子积木
    打印
    周日大悦城
    又一年毕业季
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6371707.html
Copyright © 2011-2022 走看看