【问题标题】:React expose component functionReact 暴露组件功能
【发布时间】:2017-01-04 23:11:16
【问题描述】:

基于此链接http://reactjs.cn/react/tips/expose-component-functions.html上的示例,我一直在尝试简化代码以更好地理解暴露的方法,所以我得到了以下内容,它不起作用,错误是“Uncaught TypeError: Cannot read property 'animate' of undefined",我真的不知道原因:

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);

【问题讨论】:

  • “不起作用”含糊不清。错误是什么?
  • 您的问题已解决here。看看
  • 错误是“Uncaught TypeError: Cannot read property 'animate' of undefined”

标签: javascript reactjs


【解决方案1】:

您在第一次渲染中没有对元素的引用,因为它没有安装它。

你可以做这样的事情来让它工作:

var Todos = React.createClass({
    componentDidMount: function() {
        this.refs.hello.animate();
    },
    render: function() {
        return (
                <div>
                    <Todo ref='hello' />
                </div>
        );
    }
});

componentDidMount 在组件已经被渲染(第一次)时被调用。在这里,您将获得对元素的引用

【讨论】:

  • 太感谢你了,这对我理解这些概念很有帮助!
【解决方案2】:

当前接受的答案使用 ref 字符串属性,该属性被认为是遗留的,最终将被弃用。

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

改用 ref 回调属性。

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>
        );
    }
});

【讨论】:

  • 看起来不错,但出现错误:无法读取未定义的属性“动画”
  • 错误我刚刚删除了componentDidmount,它可以工作了!
猜你喜欢
  • 2015-07-26
  • 2018-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-16
  • 1970-01-01
相关资源
最近更新 更多