![](/img/trans.png)
[英]React checkbox state management with react-bootstrap or material-ui?
[英]React Material-UI state not updating
我是React的新手,并尝试使用材质UI构建一个带抽屉的简单AppBar。
appbar和抽屉似乎正确实现,但由于某种原因,单击切换按钮时抽屉状态未更新。
我已经跟踪了材料-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
正确的上下文, 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.