![](/img/trans.png)
[英]How to access the class name of a React object in this.props.children
[英]React: How to access refs in this.props.children
我想调用子组件的函数。
是否有可能从React中的this.props.children获取引用。
var ComponentSection = React.createClass({
componentDidMount: function() {
// How to access refs in this.props.children ?
this.refs.inner.refs.specificPanel.resize();
},
render: function () {
return (
<div className="component-section" ref="inner">
{this.props.children}
</div>
);
}
});
var Panel = React.createClass({
resize: function() {
console.log('Panel resizing');
},
render: function () {
return (
<div className="Panel">
Lorem ipsum dolor sit amet
</div>
);
}
});
var MainComponent = React.createClass({
render: function () {
return (
<ComponentSection>
<Panel ref="specificPanel"></Panel>
</ComponentSection>
);
}
});
ReactDOM.render(
<MainComponent></MainComponent>,
document.getElementById('container')
);
我做了一个小小的演示: https : //jsfiddle.net/69z2wepo/26929/
提前致谢
Ref in React是组件与其所有者之间的关系,而您想要的是元素与其父元素之间的关系。 父子关系是不透明的,父级只接收渲染中的子元素 ,永远不会访问已解析的组件 。
在您的情况下, ref="specificPanel"
建立从MainComponent
到Panel
的链接。 如果你想从ComponentSection
调用Panel
方法,它应该拥有Panel
而不是作为子节点接收它们。
您可以随时使用React.Children.map
和React.createElement
(手工克隆元素,从而从原始所有者那里窃取它们)获得创意,但这会带来一些严重的潜在缺陷。 更好的方法可能是重新考虑组件树的所有权结构。
您正在尝试在<div>
而不是React组件上设置ref
。
您还可以重构代码,以便只有<ComponentSection>
需要知道<Panel>
组件,并在其渲染函数中呈现它。
var ComponentSection = React.createClass({
componentDidMount: function() {
this.refs.inner.resize();
},
render: function() {
return (
<div className="component-section">
<Panel ref="inner"/>
</div>
);
}
});
var MainComponent = React.createClass({
render: function() {
return (
<ComponentSection />
);
}
});
这是一个有效的JSFiddlle 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.