【问题标题】:Can I pass props to the children via props.children React JS我可以通过 props.children React JS 将道具传递给孩子吗
【发布时间】:2017-02-01 23:42:16
【问题描述】:

因此,如果我有一个带有渲染方法的组件,它调用 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>
    );
  }
}

我们所做的只是在场景管理器中渲染其中一个场景,但正如我们在场景管理器组件中看到的那样,我有一个名为 this._sceneManager 的“私有变量”。

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

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    是的,您需要做的就是使用您想要的其他道具克隆元素。像这样。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-19
      • 1970-01-01
      • 1970-01-01
      • 2021-09-17
      • 2018-07-29
      • 2020-08-08
      • 2017-08-22
      • 1970-01-01
      相关资源
      最近更新 更多