2016-06-28 105 views
1

我是React的新手,嘗試使用材質UI構建帶抽屜的簡單AppBar。React Material UI狀態不更新

的appbar和抽屜似乎正確實施,但由於某些原因點擊切換按鈕,當抽屜狀態不會被更新。

我跟着材料-UI的引用以及反應,所以我不知道發生了什麼事。這裏是組件的代碼:

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 

任何幫助將不勝感激!

+0

嘗試'onLeftIconButtonTouchTap = {this.handleToggle.bind(這)}' – jpopesculian

+0

@jpopesculian都能跟得上......仍然沒有 –

+0

是否有任何的錯誤安慰? – jpopesculian

回答

0

所有你需要做的,爲了讓你的狀態正確呈現是綁定你的函數的上下文。由於您使用的是ES6腳本,因此您可以通過三種方式執行此操作。

1)使用箭頭功能

handleToggle =() => { 
     this.setState({open: !this.state.open}); 
     } 

2)。指定在同時調用該函數

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> 
     ) 
     } 

綁定構造

constructor(props) { 
     super(props); 
     this.state = {open: false}; 
     this.handleToggle = this.handleToggle.bind(this); 
     } 

3)的結合,我認爲這將解決您的問題。

+0

謝謝!但出於某種原因,箭頭函數對我造成了Browserify錯誤。調用函數時在構造函數或綁定中指定綁定似乎沒有做任何事情...... –

+0

您是否檢查控制檯是否有任何錯誤 –

+0

它在=號處給我一個語法錯誤。 –

0

由於您的handleToggle函數依賴於this的正確上下文,因此您需要將它綁定到您的render函數中。

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

綁定在構造函數中handleToggle功能如下: this.handleToggle=this.handleToggle.bind(this);

相關問題