React Material-UI 状态未更新
React Material-UI state not updating
我是 React 的新手,正在尝试使用 material UI.
构建一个带抽屉的简单 AppBar。
应用栏和抽屉似乎实现正确,但由于某些原因,单击切换按钮时抽屉状态未更新。
我已经关注了 material-ui 以及 React 中的参考资料,所以我不确定发生了什么。这是组件的代码:
import React, { Component } from 'react'
import { Link } from 'react-router'
import AppBar from 'material-ui/AppBar';
import Drawer from 'material-ui/Drawer';
import MenuItem from 'material-ui/MenuItem';
class Appbar extends Component {
constructor(props) {
super(props);
this.state = {open: false};
}
handleToggle () {
this.setState({open: !this.state.open});
}
render() {
return (
<div>
<AppBar
title="Polism"
onLeftIconButtonTouchTap={this.handleToggle}
/>
<Drawer open={this.state.open}>
<MenuItem>Menu Item</MenuItem>
<MenuItem>Menu Item </MenuItem>
</Drawer>
</div>
)
}
}
export default Appbar
如有任何帮助,我们将不胜感激!
由于您的 handleToggle
函数依赖于 this
的正确上下文,您需要在 render
函数中绑定它。
onLeftIconButtonTouchTap={this.handleToggle.bind(this)}
为了让您的状态正确呈现,您需要做的就是将您的函数绑定到上下文。由于您使用的是 ES6 脚本,因此您可以通过三种方式将其两个。
1) 使用箭头函数
handleToggle = () => {
this.setState({open: !this.state.open});
}
2).在构造函数中指定绑定
constructor(props) {
super(props);
this.state = {open: false};
this.handleToggle = this.handleToggle.bind(this);
}
3) 调用函数时绑定
render() {
return (
<div>
<AppBar
title="Polism"
onLeftIconButtonTouchTap={this.handleToggle.bind(this)}
/>
<Drawer open={this.state.open}>
<MenuItem>Menu Item</MenuItem>
<MenuItem>Menu Item </MenuItem>
</Drawer>
</div>
)
}
我想这会解决你的问题。
在构造函数中绑定handleToggle函数如下:
this.handleToggle=this.handleToggle.bind(this);
我是 React 的新手,正在尝试使用 material UI.
构建一个带抽屉的简单 AppBar。应用栏和抽屉似乎实现正确,但由于某些原因,单击切换按钮时抽屉状态未更新。
我已经关注了 material-ui 以及 React 中的参考资料,所以我不确定发生了什么。这是组件的代码:
import React, { Component } from 'react'
import { Link } from 'react-router'
import AppBar from 'material-ui/AppBar';
import Drawer from 'material-ui/Drawer';
import MenuItem from 'material-ui/MenuItem';
class Appbar extends Component {
constructor(props) {
super(props);
this.state = {open: false};
}
handleToggle () {
this.setState({open: !this.state.open});
}
render() {
return (
<div>
<AppBar
title="Polism"
onLeftIconButtonTouchTap={this.handleToggle}
/>
<Drawer open={this.state.open}>
<MenuItem>Menu Item</MenuItem>
<MenuItem>Menu Item </MenuItem>
</Drawer>
</div>
)
}
}
export default Appbar
如有任何帮助,我们将不胜感激!
由于您的 handleToggle
函数依赖于 this
的正确上下文,您需要在 render
函数中绑定它。
onLeftIconButtonTouchTap={this.handleToggle.bind(this)}
为了让您的状态正确呈现,您需要做的就是将您的函数绑定到上下文。由于您使用的是 ES6 脚本,因此您可以通过三种方式将其两个。
1) 使用箭头函数
handleToggle = () => {
this.setState({open: !this.state.open});
}
2).在构造函数中指定绑定
constructor(props) {
super(props);
this.state = {open: false};
this.handleToggle = this.handleToggle.bind(this);
}
3) 调用函数时绑定
render() {
return (
<div>
<AppBar
title="Polism"
onLeftIconButtonTouchTap={this.handleToggle.bind(this)}
/>
<Drawer open={this.state.open}>
<MenuItem>Menu Item</MenuItem>
<MenuItem>Menu Item </MenuItem>
</Drawer>
</div>
)
}
我想这会解决你的问题。
在构造函数中绑定handleToggle函数如下:
this.handleToggle=this.handleToggle.bind(this);