React Material-UI状态不更新

时间:2016-06-28 18:39:14

标签: javascript reactjs frontend material-ui

我是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

非常感谢任何帮助!

3 个答案:

答案 0 :(得分:0)

由于handleToggle函数依赖于this的正确上下文,因此您需要将其绑定到render函数中。

onLeftIconButtonTouchTap={this.handleToggle.bind(this)}

答案 1 :(得分:0)

为了使状态正确呈现,您需要做的就是将函数绑定到上下文。由于您使用的是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>
          )
        }

我认为这可以解决您的问题。

答案 2 :(得分:0)

在构造函数中绑定handleToggle函数,如下所示: this.handleToggle=this.handleToggle.bind(this);