【问题标题】:Is there a way to pass props to a contained component in react?有没有办法在反应中将道具传递给包含的组件?
【发布时间】:2020-12-17 18:13:10
【问题描述】:

如果我有这样定义的组件:

export default class LinkContainer extends React.Component {
  render() {
    return (
      <div>
        <a href={this.props.baselink}>
          <h3>{this.props.title}</h3>
        </a>
        {this.props.children}
      </div>
    )
  }
}

有没有办法将this.props.baselink 传递给this.props.children 中的所有组件?

【问题讨论】:

标签: reactjs components react-props children


【解决方案1】:

您可以使用cloneElement 来执行此操作。映射您的孩子并克隆每个孩子,将第二个参数传递给 cloneElement,它将充当道具。在此示例中使用isValidElement,以防您有无法克隆的子节点,例如文本节点。

export default class LinkContainer extends React.Component {
  render() {
    return (
      <div>
        <a href={this.props.baselink}>
          <h3>{this.props.title}</h3>
        </a>
        {Children.map(this.props.children, (child) => {
          if (!isValidElement(child)) return child;
          return cloneElement(child, { baselink: this.props.baselink });
        })}
      </div>
    );
  }
}

它正在运行:https://codesandbox.io/s/vigorous-dream-9650n

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-14
    • 1970-01-01
    • 2019-06-07
    • 1970-01-01
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多