基于此链接上的示例http://reactjs.cn/react/tips/expose-component-functions.html http://reactjs.cn/react/tips/expose-component-functions.html,我一直在尝试简化代码以更好地理解公开的方法,所以我得到了以下内容,但不起作用,错误是“Uncaught 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);
您在第一个渲染中没有对该元素的引用,因为它尚未安装。
你可以做这样的事情来让它工作:
var Todos = React.createClass({
componentDidMount: function() {
this.refs.hello.animate();
},
render: function() {
return (
<div>
<Todo ref='hello' />
</div>
);
}
});
componentDidMount
当组件已经被渲染(第一次)时调用。在这里您将获得对该元素的引用
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)