zoukankan      html  css  js  c++  java
  • react children技巧总结

    在使用该技巧时,建议先看一下相关的知识,点我查看

    假如使用该属性时,想把父组件的所有属性及部分方法传递给子组件,该怎么办呢?看代码

    const Child = ({ doSomething, value }) => (
      <div onClick={() => doSomething(value)}>Click Me</div>
    );
    
    class Parent extends React.PureComponent {
      doSomething = (value) => {
        console.log('doSomething called by child with value:', value);
      }
    
      render() {
        const { children } = this.props.children;
    
        const childrenWithProps = React.Children.map(children, child =>
          React.cloneElement(child, { doSomething: this.doSomething })
        );
    
        return <div>{childrenWithProps}</div>
      }
    };
    
    ReactDOM.render(
      <Parent>
        <Child value="1" />
        <Child value="2" />
      </Parent>,
      document.getElementById('container')
    );
  • 相关阅读:
    SCP-S模拟56 C题
    NOIP模拟测试22
    NOIP模拟测试21
    NOIP模拟测试20
    NOIP模拟测试19
    网络流24题
    NOIP模拟测试18
    NOIP模拟测试16
    那些年我们颓过的游戏
    csp2019游记
  • 原文地址:https://www.cnblogs.com/94pm/p/9973277.html
Copyright © 2011-2022 走看看