了解Render Props如何帮助你构建React应用程序

134 阅读1分钟

了解Render Props如何帮助你构建React应用程序

一个常见的用于在组件之间共享状态的模式是使用children 道具。

在一个组件的JSX里面,你可以渲染{this.props.children} ,它可以自动注入任何在父组件中传递的JSX,作为一个孩子。

class Parent extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      /*...*/
    }
  }

  render() {
    return <div>{this.props.children}</div>
  }
}

const Children1 = () => {}

const Children2 = () => {}

const App = () => (
  <Parent>
    <Children1 />
    <Children2 />
  </Parent>
)

然而,这里有一个问题:父组件的状态不能从子组件中访问。

为了能够共享状态,你需要使用一个渲染道具组件,而不是将组件作为父组件的子组件传递,而是传递一个函数,然后在{this.props.children()} 。该函数可以接受参数,:

class Parent extends React.Component {
  constructor(props) {
    super(props)
    this.state = { name: 'Flavio' }
  }

  render() {
    return <div>{this.props.children(this.state.name)}</div>
  }
}

const Children1 = props => {
  return <p>{props.name}</p>
}

const App = () => <Parent>{name => <Children1 name={name} />}</Parent>

你可以使用任何道具,而不是使用children ,因为它有非常具体的含义,因此你可以在同一个组件上多次使用这种模式。

class Parent extends React.Component {
  constructor(props) {
    super(props)
    this.state = { name: 'Flavio', age: 35 }
  }

  render() {
    return (
      <div>
        <p>Test</p>
        {this.props.someprop1(this.state.name)}
        {this.props.someprop2(this.state.age)}
      </div>
    )
  }
}

const Children1 = props => {
  return <p>{props.name}</p>
}

const Children2 = props => {
  return <p>{props.age}</p>
}

const App = () => (
  <Parent
    someprop1={name => <Children1 name={name} />}
    someprop2={age => <Children2 age={age} />}
  />
)

ReactDOM.render(<App />, document.getElementById('app'))