React公开组件功能
基于此链接上的示例 http://reactjs.cn/react /tips/expose-component-functions.html ,我一直在尝试简化代码以更好地理解暴露的方法,所以我得到以下内容,这不起作用,错误是未捕获的TypeError:无法读取属性'animate'未定义我不知道原因:
Based on the example on this link http://reactjs.cn/react/tips/expose-component-functions.html, I have been trying to simplify the code to understand exposed methods better, so I got the following, which doesn't work, the error is "Uncaught TypeError: Cannot read property 'animate' of undefined" and I don't really know the reason:
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);
你没有对元素的引用第一个渲染,因为它没有安装它。
you don't have the reference to the element in the first render, because it isn't mounted it.
你可以做这样的事情让它工作:
you can do something like this to make it work:
var Todos = React.createClass({
componentDidMount: function() {
this.refs.hello.animate();
},
render: function() {
return (
<div>
<Todo ref='hello' />
</div>
);
}
});
componentDidMount
在组件已经被调用已经呈现(第一次)。在这里,您将获得元素
componentDidMount
is called when the component is already been rendered (for the first time). here you will have the reference to the element