1

Simulate the slot slot of vue in react:
Use children props: pass the structure through the component tag body
Use render props: Pass the structure through the component label attributes, and can carry data, generally use the render function attribute

children props

<A>
  <B>xxxx</B>
</A>
{this.props.children}
问题: 如果B组件需要A组件内的数据, ==> 做不到 

render props

<A render={(data) => <C data={data}></C>}></A>
A组件: {this.props.render(内部state数据)}
C组件: 读取A组件传入的数据显示 {this.props.data} 

Examples

export default class Parent extends Component {
  render() {
    return (
      <div className="parent">
        <h3>我是Parent组件</h3>
        // 此处的render是上面,类插槽的名称,可以为任意名称
        <A render={(name)=><C name={name}/>}/>
      </div>
    )
  }
}

class A extends Component {
  state = {name:'tom'}
  render() {
    console.log(this.props);
    const {name} = this.state
    return (
      <div className="a">
        <h3>我是A组件</h3>
        // 此处的render是上面,类插槽的名称,可以为任意名称
        {this.props.render(name)}
      </div>
    )
  }
}

class B extends Component {
  render() {
    console.log('B--render');
    return (
      <div className="b">
        <h3>我是B组件,{this.props.name}</h3>
      </div>
    )
  }
}

万年打野易大师
1.5k 声望1.1k 粉丝