反应:如何访问this.props.children中的参考文献
React: How to access refs in this.props.children
我想调用一个子组件的函数
有没有可能在React中从这个.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是组件与其所有者之间的关系,而您想要的是元素与其<em〉父级>素,并且永远无法访问已解析的组件。
在您的情况下,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 />
);
}
});
这是一个正在工作的JSFiddle。
相关文章:
- nextProps 总是与 this.props 相同,即使 props 在 componentWillReceiveP
- This.props.dispatch not a function - React-Redux
- React props={this.refs.something} undefined
- TypeError:undefined不是对象(正在评估'this.props')-React Nati
- JavaScript: var {left, ...props} = this.props;
- this.props.history已被弃用(react router)
- ReactJS - {this.props.children} 是未定义的
- 如何从Firebase获取数据并将其放入this.props - React
- ReactJS:this.props.data.map 不是一个函数
- 当 props 扩展时,reactjs 的 this.props 会发生变化
- 反应:如何访问this.props.children中的参考文献
- 为什么在react native中使用this.props.navigator.replace再次渲染同一场景
- 未捕获类型错误:this.props.data.map不是函数(使用超级代理)
- '&&'操作符用{this.props.children &&React.cloneElement (t
- this.props 属性的问题,即使它们存在
- 断言在' this.props.children '中只传递了一个子节点
- React Redux Reducer: 'this.props.tasks.Map不是函数'错误
- React.js对this.props.children的设计实践
- 获取TypeError: this.props在ReactJs上没有定义
- this.props.enableEdit不是执行函数时的函数错误