React公开组件功能 [英] React expose component function

查看:51
本文介绍了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

这篇关于React公开组件功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆