无法读取属性'refs'的null反应错误反应js

时间:2015-12-15 20:13:22

标签: reactjs

我正在使用React js 0.14.3,我正在尝试使用react创建一个Side Menu组件,但我不知道为什么我使用refs时“无法读取属性'refs'为null”在反应文档中: https://facebook.github.io/react/docs/more-about-refs.html 你能帮帮我吗?

'use strict';

    import React from 'react';
    import BaseComponent from './../../BaseComponent.react';
    import Menu from './SidePanelMenu';
    import MenuItem from './SidePanelMenuItem';

    class SidePanel extends BaseComponent {
        showLeft() {
            this.refs.leftmenu.show();
        }


        render() {
            return(
                <div>
                    <button onClick={this.showLeft}>Show Left Menu!</button>

                    <Menu ref="leftmenu" alignment="left">
                        <MenuItem hash="first-page">First Page</MenuItem>
                        <MenuItem hash="second-page">Second Page</MenuItem>
                        <MenuItem hash="third-page">Third Page</MenuItem>
                    </Menu>
                </div>
            );
        }
    }

    export default SidePanel;

5 个答案:

答案 0 :(得分:41)

您需要绑定this的上下文。

绑定onClick处理程序的行:

onClick={this.showLeft}

需要:

onClick={this.showLeft.bind(this)}

否则,当您致电showLeft时,它无法访问this

答案 1 :(得分:7)

改变这个:

<button onClick={this.showLeft}>Show Left Menu!</button>

对此:

<button onClick={::this.showLeft}>Show Left Menu!</button>`

答案 2 :(得分:0)

可能是这个问题。尝试

showLeft = () => {
            this.refs.leftmenu.show();
        }

constructor() {
  super();
  this.showLeft = this.showLeft.bind(this);
}

答案 3 :(得分:0)

你也可以像这样绑定它以避免No .bind() or Arrow Functions in JSX Props

的夹心错误
class SidePanel extends BaseComponent {
    constructor(props) {
        super(props);
        this.showLeft = this.showLeft.bind(this);
        this.state = {
            error: false,
        };
    }

    showLeft() {
        this.refs.leftmenu.show();
    }


    render() {
        return(
            <div>
                <button onClick={this.showLeft}>Show Left Menu!</button>

                <Menu ref="leftmenu" alignment="left">
                    <MenuItem hash="first-page">First Page</MenuItem>
                    <MenuItem hash="second-page">Second Page</MenuItem>
                    <MenuItem hash="third-page">Third Page</MenuItem>
                </Menu>
            </div>
        );
    }
}

答案 4 :(得分:0)

您的代码是用ES6编写的。与ES5不同,ES6中没有自动绑定。

因此,您必须使用this.functionName.bind(this)将函数显式绑定到组件实例。

像这样:

<button onClick={this.showLeft.bind(this)}>Show Left Menu!</button>

如果没有绑定,当您单击按钮时,按钮上的this指的是按钮本身而不是功能。因此,JavaScript会尝试在按钮元素上找到refs,这会给您带来错误。

相关问题