我想调用子组件的功能。 是否有可能从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/
提前致谢
React中的Ref是组件与其 所有者之间的关系,而您想要的是元素与 _其父对象 之间的关系。父子关系是不透明的,父级仅在渲染时接收子 元素 ,而从未访问已解析的 组件 。
就您而言,会ref="specificPanel"建立从MainComponent到的链接Panel。如果要调用Panelfrom的方法ComponentSection,则它应拥有Panels而不是将其作为子代接收。
ref="specificPanel"
MainComponent
Panel
ComponentSection
您总是可以通过React.Children.map和进行创意React.createElement(手动克隆元素,然后从原始所有者那里窃取元素),但这会带来一些严重的潜在陷阱。更好的方法可能是重新考虑组件树的所有权结构。
React.Children.map
React.createElement