隐藏和显示功能在本机反应中不起作用

时间:2018-11-16 12:35:32

标签: reactjs react-native

我尝试在抽屉中隐藏一些抽屉物品,但这不能做到。

代码:

constructor(){
 super();
 this.state = {status: true}
 }

侧边栏:

 <TouchableOpacity   
   onPress={() => {
     if(this.state.status=true)
     {
       this.setState({status:false})
     }
     else
     {
       this.setState({status:true})
     }     
     }}>

    <Text>
      hide
    </Text>

  </TouchableOpacity>

  {this.state.status=true  ? <Text>drawer</Text>:null}

引用:https://reactnativecode.com/hide-show-view-component-button-onpress/

错误:

enter image description here

3 个答案:

答案 0 :(得分:1)

  

试试这个!

constructor(){
     super();
     this.state = {status: true}
     }

侧边栏:

setStateByClick = () => {
    if(this.state.status)
         {
           this.setState({status:false})
         }
         else
         {
           this.setState({status:true})
         } 
    }

<TouchableOpacity  
   style={{ height:30, marginTop:10, marginLeft:70,}}  
   onPress={() => this.setStateByClick}>

    <Text style={{color: 'white',fontWeight:'bold',}} >
      hide
    </Text>

  </TouchableOpacity>

  {this.state.status  ? <Text>drawer</Text> : null }

希望这对您有用!

答案 1 :(得分:1)

constructor(){
 super();
 this.state = {status: true}

 }

注意:请不要在this.state.status === true条件下使用if,而只需使用this.state.status以获得更好的代码

constructor(){
   super();
     this.state = {status: true}
   }



setSidebarState(){
    if(this.state.status)
         {
           this.setState({status:false})
         }
         else
         {
           this.setState({status:true})
         } 
    }

   <TouchableOpacity  
      style={{ height:30, marginTop:10, marginLeft:70,}}  
      onPress={() => this.setSidebarState()}>

       <Text style={{color: 'white',fontWeight:'bold',}} >
         hide
       </Text>

     </TouchableOpacity>

     {this.state.status  ? <Text>drawer</Text> : null }

答案 2 :(得分:1)

使用它更具可读性

render(){
  const { status } = this.state;
  return(
    <View>
      <TouchableOpacity  onPress={ () => this.setState({status:!status})}>
        <Text>Hey</Text>
      </TouchableOpacity>

     {status ? <Text>drawer</Text> : null}
    </View>
  )
}