How to pass props to {this.props.children}

后端 未结 26 4028
猫巷女王i
猫巷女王i 2020-11-21 23:42

I\'m trying to find the proper way to define some components which could be used in a generic way:


  
  

        
26条回答
  •  我在风中等你
    2020-11-22 00:25

    Render props is most accurate approach to this problem. Instead of passing the child component to parent component as children props, let parent render child component manually. Render is built-in props in react, which takes function parameter. In this function you can let parent component render whatever you want with custom parameters. Basically it does the same thing as child props but it is more customizable.

    class Child extends React.Component {
      render() {
        return 
    Child

    Click me

    {this.props.a}
    ; } } class Parent extends React.Component { doSomething(){ alert("Parent talks"); } render() { return
    Parent {this.props.render({ anythingToPassChildren:1, doSomething: this.doSomething})}
    ; } } class Application extends React.Component { render() { return
    }/>
    ; } }

    Example at codepen

提交回复
热议问题