【问题标题】:How make child components of a child component have refs that the first-level child can use?如何使子组件的子组件具有一级子可以使用的引用?
【发布时间】:2016-11-22 21:34:30
【问题描述】:
如果我有以下 JSX,Child 的 refs 为空:
<Parent>
<Child ref="first">
<GrandChild ref="parentSeesThisNotChild" />
</Child>
</Parent>
我希望Child 组件在其refs 中获得GrandChild。我该怎么做?
【问题讨论】:
标签:
javascript
reactjs
react-jsx
jsx
【解决方案1】:
您必须修改Child 组件代码:
const Child = React.createClass({
render() {
const childrenWithProps = React.Children.map(this.props.children, (child) => {
return React.cloneElement(child, {
ref: child.ref,
});
});
return (
<div>
<h1>Child</h1>
{childrenWithProps}
</div>
)
},
});