Question: React expose component function

Question

React expose component function

Answers 2
Added at 2017-01-05 00:01
Tags
Question

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);
Answers
nr: #1 dodano: 2017-01-05 00:01

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 is called when the component is already been rendered (for the first time). here you will have the reference to the element

nr: #2 dodano: 2017-01-05 00:01

The currently accepted answer uses the ref string attribute which is considered legacy 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>
        );
    }
});
Source Show
◀ Wstecz