我可以通过props.children React JS将道具传递给孩子们吗

Can I pass props to the children via props.children React JS

本文关键字:孩子们 props 可以通过 children React JS      更新时间:2023-09-26

因此,如果我有一个组件的渲染方法调用this.props.children来渲染任何子级,我可以将任何道具从父级传递给它试图渲染的子级吗?

例如,考虑以下内容:

import React, { Component } from 'react';
import CoreSceneManager     from '../engine/scene_manager';
export default class SceneManager extends Component {
  constructor(props) {
    super(props);
    this._sceneManager = new CoreSceneManager();
  }
  componentWillMount() {
    this._sceneManager.registerScenes(this.props.children);
  }
  componentWillUnmount() {
    this._sceneManager.exit();
  }
  render() {
    return(
      <div>
        {this._sceneManager.getCurrentScene()}
      </div>
    );
  }
}

这样使用:

export default class SceneHandeling extends Component {
  constructor(props) {
    super(props)
  }
  render() {
    return(
      <Loop>
        <SceneManager>
          <ExampleSceneA />
          <ExampleSceneB />
        </SceneManager>
      </Loop>
    );
  }
}

我们所做的是在场景管理器中只渲染其中一个场景,但正如我们在场景管理程序组件中所看到的;私有变量";称为CCD_ 1。

我想把这个传给孩子们,在这种情况下是ExampleSceneB,因为这就是呈现到页面上的内容。

你所需要做的就是用你想要的额外道具克隆元素。像这样。

componentWillMount() {
    const childrenWithProps = React.Children.map(this.props.children,
        (child) => React.cloneElement(child, {
            sceneManager: this._sceneManager
        })
    );
    this._sceneManager.registerScenes(childrenWithProps);
}