Component Function Response

Based on the example at this link http://reactjs.cn/react/tips/expose-component-functions.html , I tried to simplify the code in order to better understand the available methods, so I got the following which does not work, error "Uncaught TypeError : It is not possible to read the "animate" property from undefined ", and I really don't 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); 
+5
source share
2 answers

you don’t have an element reference in the first render because it is not set.

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 is called when the component is already displayed (for the first time). here you will have a link to the item

+2
source

The currently accepted answer uses the string attribute ref, which is considered deprecated and will eventually be deprecated.

http://reactjs.cn/react/docs/more-about-refs.html#the-ref-string-attribute

Use the ref callback attribute instead.

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> ); } }); 
+1
source

Source: https://habr.com/ru/post/1262325/


All Articles