根据此链接http://reactjs.cn/react/tips/expose-component-functions.html上的示例,我一直在尝试简化代码以更好地理解公开的方法,因此我得到了以下内容,但不起作用,错误是&#34 ;未捕获的TypeError:无法读取属性' animate'未定义"而且我真的不知道原因:
var Todo = React.createClass({
render: function() {
return <div></div>;
},
//this component will be accessed by the parent through the `ref` attribute
animate: function() {
console.log('Pretend is animating');
}
});
var Todos = React.createClass({
render: function() {
return (
<div>
<Todo ref='hello' />
{this.refs.hello.animate()}
</div>
);
}
});
ReactDOM.render(<Todos />, app);
答案 0 :(得分:3)
你没有在第一个渲染中引用元素,因为它没有被安装。
你可以做这样的事情来使其发挥作用:
var Todos = React.createClass({
componentDidMount: function() {
this.refs.hello.animate();
},
render: function() {
return (
<div>
<Todo ref='hello' />
</div>
);
}
});
在已经渲染组件时(第一次)调用 componentDidMount
。在这里,您将获得元素
答案 1 :(得分:1)
当前接受的答案使用ref string属性,该属性被认为是遗留的,最终将被弃用。
http://reactjs.cn/react/docs/more-about-refs.html#the-ref-string-attribute
改为使用ref callback属性。
http://reactjs.cn/react/docs/more-about-refs.html#the-ref-callback-attribute
var Todos = React.createClass({
render: function() {
return (
<div>
<Todo ref= {function(n) {n.animate();}} />
</div>
);
}
});