我使用的是React js 0.14.3,我试图使用React创建一个Side Menu组件,但我不知道为什么我在使用React文档中的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;
您需要绑定this
的上下文。
绑定onClick
处理程序的行:
onClick={this.showLeft}
需要:
onClick={this.showLeft.bind(this)}
否则,当您调用showLeft
时,它无法访问this
。
更改此项:
<button onClick={this.showLeft}>Show Left Menu!</button>
对此:
<button onClick={::this.showLeft}>Show Left Menu!</button>`
您的代码是用ES6编写的。与ES5不同,ES6中没有自动绑定。
因此,必须使用this.functionName.bind(this)
将函数显式绑定到组件实例。
像这样:
<button onClick={this.showLeft.bind(this)}>Show Left Menu!</button>
在没有绑定的情况下,当您单击按钮时,按钮上的this
指的是按钮本身,而不是功能。因此,JavaScript试图在button元素上找到refs
,这会给您带来错误。
可能是这个问题。尝试
showLeft = () => {
this.refs.leftmenu.show();
}
或
constructor() {
super();
this.showLeft = this.showLeft.bind(this);
}
您也可以这样绑定它,以避免No .bind() or Arrow Functions in JSX Props
:的esint错误
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>
);
}
}