Hide/Show components in react native

后端 未结 24 1959
囚心锁ツ
囚心锁ツ 2020-12-07 08:43

I\'m really new to React Native and I\'m wondering how can I hide/show a component.
Here\'s my test case:



        
24条回答
  •  囚心锁ツ
    2020-12-07 09:19

    Most of the time i'm doing something like this :

    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        this.state = {isHidden: false};
        this.onPress = this.onPress.bind(this);
      }
      onPress() {
        this.setState({isHidden: !this.state.isHidden})
      }
      render() {
        return (
          
    
            {this.state.isHidden ?  : null}
    
            

    If you're kind of new to programming, this line must be strange to you :

    {this.state.isHidden ?  : null}
    

    This line is equivalent to

    if (this.state.isHidden)
    {
      return (  );
    }
    else
    {
      return null;
    }
    

    But you can't write an if/else condition in JSX content (e.g. the return() part of a render function) so you'll have to use this notation.

    This little trick can be very useful in many cases and I suggest you to use it in your developments because you can quickly check a condition.

    Regards,

提交回复
热议问题