Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

168
Vistas
React expose component function

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);
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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

over 4 years ago · Santiago Trujillo Denunciar

0

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>
        );
    }
});
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda