我有一个组件,我想检查它的子项,如果孩子是一个特定的组件,我想在其上设置一些其他的道具定义:
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>
..
我想检查包装的孩子。我怎样才能实现它?
答案 0 :(得分:0)
我在这个链接中找到了一个解决方案:
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);