【问题标题】:Pass some props from parent to grangchild component将一些道具从父组件传递给孙组件
【发布时间】:2017-07-11 13:49:21
【问题描述】:

我有一个组件,我想检查它的子组件,如果子组件是特定组件,我想在它上面设置一些其他的 props 定义,如下所示:

import React from 'react'

function RadioOption(props) {
  return (
    <label>
      <input type="radio" value={props.value} name={props.name} />
      {props.label}
    </label>
  )
}

function renderChildren(props) {
  return React.Children.map(props.children, child => {
    if (child.type === RadioOption)
      return React.cloneElement(child, {
        name: props.name
      })
    else
      return child
  })
}

function RadioGroup(props) {
  return (
    <div class="radio-group">
      {renderChildren(props)}
    </div>
  )
}

function WhereImUsingRadioGroups() {
  return (
    <RadioGroup name="blizzard-games">
      <RadioOption label="Warcraft 2" value="wc2" />
      <RadioOption label="Warcraft 3" value="wc3" />
      <RadioOption label="Starcraft 1" value="sc1" />
      <RadioOption label="Starcraft 2" value="sc2" />
    </RadioGroup>
  )
}

在这个例子中一切都很好,但是当我想把孩子放在一个包装器中时,我无法检查它。我可以访问包装器。

  ..

<RadioGroup name="blizzard-games">
  <span className="wrapper"><RadioOption label="Warcraft 2" value="wc2" /></span>
  <RadioOption label="Warcraft 3" value="wc3" />
  <RadioOption label="Starcraft 1" value="sc1" />
  <RadioOption label="Starcraft 2" value="sc2" />
</RadioGroup>
..

我想检查包装器的孩子,嗯。我怎样才能实现它?

【问题讨论】:

  • 也许您的 RadioOption 组件可以处理有条件地在包装器内呈现其标签。这将为您提供可以访问所有道具的单一后代。

标签: javascript reactjs components


【解决方案1】:

我在此链接中找到了解决方案:

https://medium.com/@skwee357/the-land-of-undocumented-react-js-the-context-99b3f931ff73

谢谢,我解决了这个问题。有了上下文,我现在可以将道具从父母传递给孙子。

页面中的示例:

var App = React.createClass({
  render: function() {
    return (
      <Grandparent>
        { function() {
          return (<Parent>
            <Child/>
          </Parent>)
        }}
      </Grandparent>
    );
  }
});
var Grandparent = React.createClass({  
  childContextTypes: {
    name: React.PropTypes.string.isRequired
  },
  getChildContext: function() {
    return {name: 'Jack'};
  },

  render: function() {
    var children = this.props.children;
    children = children();
    return children;
  }

});
var Parent = React.createClass({
  render: function() {
    return this.props.children;
  }
});
var Child = React.createClass({
  contextTypes: {
    name: React.PropTypes.string.isRequired
  },
  render: function() {
    return <div>My name is {this.context.name}</div>;
  }
});
React.render(<App/>, document.body);

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-12
  • 2021-07-04
  • 2021-04-12
  • 2020-11-23
  • 2020-09-01
相关资源
最近更新 更多