react传递props给孩子

IT技术 reactjs
2021-04-27 03:48:33

我正在尝试将额外的props传递给 this.props.children,我看到了这个答案how to pass props to children with React.cloneElement?

出于某种原因,虽然我没有收到任何错误,但我看不到props

所以我有这个状态

this.state = {
    open: true
}

我想把它传递给 this.props.children,这就是我到目前为止所做的:

{
    React.Children.map(this.props.children, child =>
        React.cloneElement(child, {sidebarState: this.state.open}))
}

当我在孩子身上使用 console.logging this.props 时,我看不到我的新props。

--- 编辑 --- 在孩子中它看起来像这样:

render() {
    console.log(this.props)
    // other code
}

顺便说一句,我正在使用 react 16.0

2个回答

这是一个例子。

之前(没有将props传递给children):

    <div className="layout">
      {children}
    </div>

之后(将额外props1props2props传递给每个孩子):

    <div className="layout">
      {
        React.Children.map(children, (child) => {
          return React.cloneElement(child, {
            props1: 1,
            props2: 2,
          });
        })
      }
    </div>

props1props2与每个孩子的现有props合并。

关于 TypeScript 类型,您必须使用React.ReactElement而不是,React.ReactNode否则 TS 编译器会抱怨React.Children.map(或 ts-ignore it):

type Props = {
  children: React.ReactElement;
};

有关更多解释,请参阅https://medium.com/better-programming/passing-data-to-props-children-in-react-5399baea0356,这对我了解如何去做有很大帮助!(#mediumPaywall)

有两种方法可以将 props 传递给孩子:

作为函数的孩子

子元素可以是一个函数,而不是一个 React 元素。

调用子函数:

const List = ({ children, sidebarState }) => (
  <ul>
  {
    children(sidebarState)
  }
  </ul>
);

传递给孩子一个函数:

<List sidebarState={sidebarState}>
  {
    (sidebarState) => (
      <Item sidebarState={sidebarState} />
    )
  }
</List>

工作示例:

React.cloneElement

工作示例: