使用状态隐藏/显示视图

时间:2017-03-15 05:24:05

标签: reactjs react-native

我想要隐藏“完成”'我的react-native-navbar上的按钮基于状态

this.state = {
    doneButtonHidden: true
}

我的状态设置为真

doneButtonHidden(hidden) {
    if (!hidden) {
        return {
            title: 'Done',
            tintColor: '#ff9000'
        }
    }
}

但是,如果我切换doneButtonHidden和hot reload的值,它会保持隐藏并且不会更新

<NavigationBar
    title={{title: 'Friends', tintColor: '#ff9000'}}
    rightButton={this.doneButtonHidden(this.state.doneButtonHidden)}
/>

我做错了什么?

1 个答案:

答案 0 :(得分:1)

两件事:
- 更改状态时需要使用setState()
见:https://facebook.github.io/react-native/docs/state.html
  - 当你说this.state.doneButtonHidden时,this引用当前对象,而不是词汇。
我会做类似的事情:

render(){
  // This way you can pass a boolean into
  // the doneButtonHidden function.
  let hidden = this.state.doneButtonHidden ? true : false;
  return(
    ... more stuff here ...
    <NavigationBar
      title={{title: 'Friends', tintColor: '#ff9000'}}
      // If use you use arrow function syntax, you have access
      // to lexical this.
      rightButton={() => {
              // If 'rightButton' is supposed to change
              // state use this line.
              this.setState({doneButtonHidden: false})
              doneButtonHidden(hidden)} 
          }
    />
    ... more stuff here ...
  );
}