从React中的子进程访问包装器组件的方法

时间:2018-02-13 08:01:23

标签: reactjs parent-child

假设您有一个呈现文本的子组件,如下所示:

 export const RatingsGoneBetter = () => (
    <TestContainer>
      <section>
        <h1>What could&rsquo;ve gone better with {this.props.getName()}?</h1>
      </section>
    </TestContainer>
)

父母......

class TestContainer extends React.Component {
    constructor (props) {
      super(props)
  }

    getName () {
      const { userId, chef, john } = this.props

      if (userId === 50) {
          return john.name
      } else if (userId === 1) {
          return chef.name
      }
  }

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

问题

如何调用子节点中的getName方法来呈现正确的名称?

1 个答案:

答案 0 :(得分:1)

要将props添加到children元素,您可以使用React.cloneElement。您还需要将子项分成单独的组件,以便您可以使用cloneElement

访问传递给它们的道具。

相关代码段:

const RatingsGoneBetter = props => (
  <TestContainer userId={1} chef={{ name: "codesandbox" }}>
    <Sample />
  </TestContainer>
);

const Sample = props => {
  return (
    <section>
      <h1>What could&rsquo;ve gone better with {props.getName()}?</h1>
    </section>
  );
};

和TestContainer

render () {
  return (
    <div>{React.Children.map(this.props.children, (child) => {
                return React.cloneElement(child, {getName: this.getName()}, null);
          })}
    </div>
  )
}

<强> Working CodeSandbox

相关问题