【问题标题】:Hide/Show components in react native在本机反应中隐藏/显示组件
【发布时间】:2015-07-27 19:27:26
【问题描述】:

我是 React Native 的新手,我想知道如何隐藏/显示组件。
这是我的测试用例:

<TextInput
    onFocus={this.showCancel()}
    onChangeText={(text) => this.doSearch({input: text})} />

<TouchableHighlight 
    onPress={this.hideCancel()}>
    <View>
        <Text style={styles.cancelButtonText}>Cancel</Text>
    </View>
</TouchableHighlight>

我有一个TextInput 组件,我想要的是在输入获得焦点时显示TouchableHighlight,然后在用户按下取消按钮时隐藏TouchableHighlight

我不知道如何“访问”TouchableHighlight 组件以便在我的函数showCancel/hideCancel 中隐藏/显示它。
另外,如何从一开始就隐藏按钮?

【问题讨论】:

    标签: javascript react-native


    【解决方案1】:

    在你的渲染函数中:

    { this.state.showTheThing && 
      <TextInput/>
    }
    

    那就这样吧:

    this.setState({showTheThing: true})  // to show it  
    this.setState({showTheThing: false}) // to hide it
    

    【讨论】:

    • 这对我有用。但是,我不确定为什么当我执行{ this.state.showTheThing &amp;&amp; (&lt;Text&gt;foo&lt;/Text&gt; &amp;&amp; &lt;Text&gt;bar&lt;/Text&gt;)} 之类的操作时,UI 中只显示“栏”。我希望会显示“foo”和“bar”。我需要做的是打电话给{ this.state.showTheThing &amp;&amp; (&lt;Text&gt;foo&lt;/Text&gt;} { this.state.showTheThing &amp;&amp; (&lt;Text&gt;bar&lt;/Text&gt;}
    • 也许这行得通?因为逻辑 &amp;&amp; 没有组合元素 { this.state.showTheThing &amp;&amp; (&lt;View&gt;&lt;Text&gt;foo&lt;/Text&gt;&lt;Text&gt;bar&lt;/Text&gt;&lt;/View&gt;)}
    • 这对我有用,我想在用户上传他们的个人资料图片时显示“下一步”按钮。所以我的代码是:{this.state.hasPic &amp;&amp; &lt;Button title="Go to next step" onPress={this._nextStep} /&gt;}
    • 对于任何难以显示多个组件的人,请使用片段包装您的组件。例如。 &lt;React.Fragment&gt;&lt;Text&gt;Foo&lt;/Text&gt;&lt;Text&gt;Bar&gt;&lt;/Text&gt;&lt;/React.Fragment&gt;
    【解决方案2】:

    我会这样做:

    var myComponent = React.createComponent({
    
        getInitialState: function () {
            return {
                showCancel: false,
            };
        },
    
        toggleCancel: function () {
            this.setState({
                showCancel: !this.state.showCancel
            });
        }
    
        _renderCancel: function () {
            if (this.state.showCancel) {
                return (
                    <TouchableHighlight 
                        onPress={this.toggleCancel()}>
                        <View>
                            <Text style={styles.cancelButtonText}>Cancel</Text>
                        </View>
                    </TouchableHighlight>
                );
            } else {
                return null;
            }
        },
    
        render: function () {
            return (
                <TextInput
                    onFocus={this.toggleCancel()}
                    onChangeText={(text) => this.doSearch({input: text})} />
                {this._renderCancel()}          
            );
        }
    
    });
    

    【讨论】:

    • 非常感谢,我只需要做一个小改动:onFocus={() => this.showCancel() } 这需要一个回调函数。
    • 仅在将 return '' 更改为 return null 后对我有用
    • 你也可以{someBoolVal &amp;&amp; &lt;Component /&gt;},只有当bool值为真时才会显示。
    • 这是最好的答案
    • 我不知道这是公认的答案,它没有实现原始所需的功能显示/隐藏,而是添加/删除
    【解决方案3】:

    在 react 或 react native 中,组件隐藏/显示或添加/删除的方式不像在 android 或 iOS 中那样工作。我们大多数人认为会有类似的策略,比如

    View.hide = true or parentView.addSubView(childView)
    

    但是反应原生工作的方式完全不同。实现这种功能的唯一方法是将组件包含在 DOM 中或从 DOM 中删除。

    在此示例中,我将根据按钮单击设置文本视图的可见性。

    这个任务背后的想法是创建一个名为 state 的状态变量,当按钮点击事件发生时,它的初始值设置为 false,然后它的值切换。现在我们将在创建组件的过程中使用这个状态变量。

    import renderIf from './renderIf'
    
    class FetchSample extends Component {
      constructor(){
        super();
        this.state ={
          status:false
        }
      }
    
      toggleStatus(){
        this.setState({
          status:!this.state.status
        });
        console.log('toggle button handler: '+ this.state.status);
      }
    
      render() {
        return (
          <View style={styles.container}>
            {renderIf(this.state.status)(
              <Text style={styles.welcome}>
                I am dynamic text View
              </Text>
            )}
    
            <TouchableHighlight onPress={()=>this.toggleStatus()}>
              <Text>
                touchme
              </Text>
            </TouchableHighlight>
          </View>
        );
      }
    }
    

    在这个 sn-p 中唯一需要注意的是renderIf,它实际上是一个函数,它将根据传递给它的布尔值返回传递给它的组件。

    renderIf(predicate)(element)
    

    renderif.js

    'use strict';
    const isFunction = input => typeof input === 'function';
    export default predicate => elemOrThunk =>
      predicate ? (isFunction(elemOrThunk) ? elemOrThunk() : elemOrThunk) : null;
    

    【讨论】:

    • 聪明 :) thunk 的用例是什么?
    • 哈哈。太棒了!
    • 此解决方案适用于对话框仅在需要时才呈现的用例。泰!
    • 如果您需要保持状态,这将不起作用,删除元素重置他的状态。所以每次你再次渲染就像你再次创建组件一样。
    • touchme(touchablehighlight)组件上移,如何防止上移?
    【解决方案4】:

    在 render() 中,您可以有条件地显示 JSX 或返回 null,如下所示:

    render(){
        return({yourCondition ? <yourComponent /> : null});
    }
    

    【讨论】:

    • 第 2 行需要括号。
    • 感谢您提供最简单的解决方案
    【解决方案5】:

    React Native 的布局支持 display 属性,类似于 CSS。 可能的值:noneflex(默认值)。 https://facebook.github.io/react-native/docs/layout-props#display

    <View style={{display: 'none'}}> </View>
    

    【讨论】:

    • 小心不要将它与position: absolute 一起使用,它实际上并没有隐藏它! 0.54 - 0.59(至少)的已知错误:github.com/facebook/react-native/issues/18415
    • 这是适用于我的情况的答案,它必须以编程方式按下隐藏按钮。我认为其他许多解决方案都不能解决我的具体问题,好像按钮没有呈现,它不能被点击。
    【解决方案6】:

    大部分时间我都在做这样的事情:

    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 (
          <View style={styles.myStyle}>
    
            {this.state.isHidden ? <ToHideAndShowComponent/> : null}
    
            <Button title={this.state.isHidden ? "SHOW" : "HIDE"} onPress={this.onPress} />
          </View>
        );
      }
    }
    

    如果您是编程新手,那么这行代码对您来说一定很陌生:

    {this.state.isHidden ? <ToHideAndShowComponent/> : null}
    

    这一行相当于

    if (this.state.isHidden)
    {
      return ( <ToHideAndShowComponent/> );
    }
    else
    {
      return null;
    }
    

    但是你不能在 JSX 内容中编写 if/else 条件(例如渲染函数的 return() 部分),所以你必须使用这种表示法。

    这个小技巧在很多情况下都非常有用,我建议你在开发中使用它,因为你可以快速检查一个条件。

    问候,

    编辑:对于更直接的合成器,您可以使用{this.state.isHidden &amp;&amp; &lt;ToHideAndShowComponent/&gt;}。这里,左边的操作数在右边的操作数之前被评估,所以如果isHidden 为假,那么组件将不会出现。

    【讨论】:

    • 您能否详细说明您是如何定义
    • @Ritveak by 他的意思是你自己想要隐藏或显示的元素......它不是一个定义的元素,它只是一个例子。
    【解决方案7】:

    我需要在两个图像之间切换。在它们之间进行有条件的切换时,会出现 5 秒的延迟,但没有显示图像。

    我正在使用来自被低估的 amos 答案的方法。发布为新答案,因为很难以正确的格式将代码放入评论中。

    渲染函数:

    <View style={styles.logoWrapper}>
      <Image
        style={[styles.logo, loading ? styles.hidden : {}]}
        source={require('./logo.png')} />
      <Image
        style={[styles.logo, loading ? {} : styles.hidden]}
        source={require('./logo_spin.gif')} />
    </View>
    

    样式:

    var styles = StyleSheet.create({
      logo: {
        width: 200,
        height: 200,
      },
      hidden: {
        width: 0,
        height: 0,
      },
    });
    

    【讨论】:

    • 这会将组件保存在内存中,这可能是大型组件的问题。为什么不使用上面的好例子呢?他们将插入正确的图片并完全删除另一张...
    • 当您尝试创建动画微调器时,这些示例中的任何一个都无法正常工作。就像我在关于android试图将img切换为anim gif的回答中已经提到的那样,当没有显示png或gif时会导致5s延迟。我相信延迟是由于将 gif 加载到内存中造成的,这可能需要一些时间。然而,iOS 似乎在这里做得更好。如果你不相信我,你自己试试。
    • 当然,正如所指出的,这并不是每个组件的最佳解决方案。但是恕我直言,加载微调器就可以了。当用户切换到另一个页面时,它最终会被卸载。
    【解决方案8】:

    隐藏显示Activity Indicator的父视图

    constructor(props) {
      super(props)
    
      this.state = {
        isHidden: false
      }  
    } 
    

    隐藏显示作为关注

    {
       this.state.isHidden ?  <View style={style.activityContainer} hide={false}><ActivityIndicator size="small" color="#00ff00" animating={true}/></View> : null
    }
    

    完整参考

    render() {
        return (
           <View style={style.mainViewStyle}>
              <View style={style.signinStyle}>
               <TextField placeholder='First Name' keyboardType='default' onChangeFirstName={(text) => this.setState({firstName: text.text})}/>
               <TextField placeholder='Last Name' keyboardType='default' onChangeFirstName={(text) => this.setState({lastName: text.text})}/>
               <TextField placeholder='Email' keyboardType='email-address' onChangeFirstName={(text) => this.setState({email: text.text})}/>
               <TextField placeholder='Phone Number' keyboardType='phone-pad' onChangeFirstName={(text) => this.setState({phone: text.text})}/>
               <TextField placeholder='Password' secureTextEntry={true} keyboardType='default' onChangeFirstName={(text) => this.setState({password: text.text})}/>
               <Button  style={AppStyleSheet.buttonStyle} title='Sign up' onPress={() => this.onSignupPress()} color='red' backgroundColor='black'/>
              </View>
              {
                this.state.isHidden ?  <View style={style.activityContainer}><ActivityIndicator size="small" color="#00ff00" animating={true}/></View> : null
              }
          </View>
       );
    }
    

    On 按钮按下设置状态如下

    onSignupPress() {
      this.setState({isHidden: true})
    }
    

    当你需要隐藏时

    this.setState({isHidden: false})
    

    【讨论】:

      【解决方案9】:

      随便用

      style={ width:0, height:0 } // to hide
      

      【讨论】:

      • 如果您在答案中添加一些上下文/细节会很有帮助。
      • 假设您有一种机制来决定隐藏哪个组件,这个答案非常有用。你可以用 style={{width:0, height:0}} 的 View 包装你想要隐藏的任何组件。
      • 如何将元素恢复到原来的宽高?
      • 不明白为什么这会被否决,但在许多情况下这是个好建议。我需要在动画和非动画 gif 之间切换。有条件的切换 img 会导致屏幕上没有 img 的延迟。作为修复的一部分,我同时显示了两个 img,但应该隐藏的那个的宽度和高度为零。
      • 这会将组件保留在内存中,这可能是大型组件的问题。为什么不使用上面的好例子呢?他们完全插入和移除组件...
      【解决方案10】:

      我有同样的问题,我想显示/隐藏视图,但我真的不希望 UI 在添加/删除内容或处理重新渲染时跳来跳去。

      我写了一个简单的组件来为我处理它。默认动画,但易于切换。我把它放在GitHubNPM 上,并附上自述文件,但所有代码都在下面。

      npm install --save react-native-hideable-view

      import React, { Component, PropTypes } from 'react';
      import { Animated  } from 'react-native';
      
      class HideableView extends Component {
        constructor(props) {
          super(props);
          this.state = {
            opacity: new Animated.Value(this.props.visible ? 1 : 0)
          }
        }
      
        animate(show) {
          const duration = this.props.duration ? parseInt(this.props.duration) : 500;
          Animated.timing(
            this.state.opacity, {
              toValue: show ? 1 : 0,
              duration: !this.props.noAnimation ? duration : 0
            }
          ).start();
        }
      
        shouldComponentUpdate(nextProps) {
          return this.props.visible !== nextProps.visible;
        }
      
        componentWillUpdate(nextProps, nextState) {
          if (this.props.visible !== nextProps.visible) {
            this.animate(nextProps.visible);
          }
        }
      
        render() {
          if (this.props.removeWhenHidden) {
            return (this.visible && this.props.children);
          }
          return (
            <Animated.View style={{opacity: this.state.opacity}}>
              {this.props.children}
            </Animated.View>
          )
        }
      }
      
      HideableView.propTypes = {
        visible: PropTypes.bool.isRequired,
        duration: PropTypes.number,
        removeWhenHidden: PropTypes.bool,
        noAnimation: PropTypes.bool
      }
      
      export default HideableView;
      

      【讨论】:

      • 不错,正是我想要的:)
      • 这种方法效果最好,并且当您将其他具有生命周期的组件放入视图中时,它的行为就像一个正确的视图(不适用于visible &amp;&amp; (...)
      【解决方案11】:

      另一个选项是通过样式应用绝对定位,将隐藏的组件设置为屏幕外坐标:

      <TextInput
          onFocus={this.showCancel()}
          onChangeText={(text) => this.doSearch({input: text})}
          style={this.state.hide ? {position: 'absolute', top: -200} : {}}
      />
      

      与之前的一些建议不同,这会将您的组件隐藏在视图之外,但也会呈现它(将其保留在 DOM 中),从而使其真正不可见

      【讨论】:

      【解决方案12】:
      constructor(props) {
          super(props);
          this.state = {
            visible: true,
      }
      }
      

      将可见声明为 false,因此默认模式/视图是隐藏的

      示例 = () => {

       this.setState({ visible: !this.state.visible })
      

      }

      **函数调用**

      {this.state.visible == false ?
              <View>
                  <TouchableOpacity
                    onPress= {() => this.example()}>   // call function
                                <Text>
                                  show view
                                </Text>
                  </TouchableOpacity>
      
      </View>
      :
       <View>
          <TouchableOpacity
                    onPress= {() => this.example()}>
                                <Text>
                                  hide view
                                </Text>
                  </TouchableOpacity>
      </View> 
       }
      

      【讨论】:

        【解决方案13】:

        如果您需要组件保持加载但隐藏,您可以将不透明度设置为 0。(例如,我需要这个用于展览相机)

        //in constructor    
        this.state = {opacity: 100}
        
        /in component
        style = {{opacity: this.state.opacity}}
        
        //when you want to hide
        this.setState({opacity: 0})
        

        【讨论】:

          【解决方案14】:
          // You can use a state to control wether the component is showing or not
          const [show, setShow] = useState(false); // By default won't show
          
          // In return(
          {
              show && <ComponentName />
          }
          
          /* Use this to toggle the state, this could be in a function in the 
          main javascript or could be triggered by an onPress */
          
          show == true ? setShow(false) : setShow(true)
          
          // Example:
          const triggerComponent = () => {
              show == true ? setShow(false) : setShow(true)
          }
          
          // Or
          <SomeComponent onPress={() => {show == true ? setShow(false) : setShow(true)}}/>
          
          

          【讨论】:

          • 虽然此代码可以解决 OP 的问题,但最好包含关于您的代码如何解决 OP 问题的说明。这样,未来的访问者可以从您的帖子中学习,并将其应用到他们自己的代码中。 SO 不是编码服务,而是知识资源。此外,高质量、完整的答案更有可能获得支持。这些功能,以及所有帖子都是独立的要求,是 SO 作为一个平台的一些优势,使其与论坛区分开来。您可以编辑以添加其他信息和/或使用源文档补充您的解释。
          • 更新,解释更多。希望对您有所帮助!
          【解决方案15】:

          您可以使用我的模块react-native-display 来显示/隐藏组件。

          【讨论】:

            【解决方案16】:

            以下示例是使用 Hooks 在 typescript 中编码。

            import React, { useState, useEffect } from "react";
            
            ........
            
            const App = () => {
            
               const [showScrollView, setShowScrollView] = useState(false);
            
               ......
            
               const onPress = () => {
                // toggle true or false
                setShowScrollView(!showScrollView);
              }
            
              ......
            
                  </MapboxGL.ShapeSource>
                    <View>{showScrollView ? (<DetailsScrollView />) : null}</View>
                  </MapboxGL.MapView>
              ......
            
            }
            

            【讨论】:

              【解决方案17】:

              如果您不想从页面中删除组件,我会保证使用 opacity-method,例如隐藏 WebView。

              <WebView
                 style={{opacity: 0}} // Hide component
                 source={{uri: 'https://www.google.com/'}}
               />
              

              如果您需要向第 3 方网站提交表单,这很有用。

              【讨论】:

                【解决方案18】:

                我只是使用下面的方法来隐藏或查看按钮。希望它会帮助你。只需更新状态并添加隐藏 css 对我来说就足够了

                constructor(props) {
                   super(props);
                      this.state = {
                      visibleStatus: false
                   };
                }
                updateStatusOfVisibility () {
                   this.setStatus({
                      visibleStatus: true
                   });
                }
                hideCancel() {
                   this.setStatus({visibleStatus: false});
                }
                
                render(){
                   return(
                    <View>
                        <TextInput
                            onFocus={this.showCancel()}
                            onChangeText={(text) => {this.doSearch({input: text}); this.updateStatusOfVisibility()}} />
                
                         <TouchableHighlight style={this.state.visibleStatus ? null : { display: "none" }}
                             onPress={this.hideCancel()}>
                            <View>
                                <Text style={styles.cancelButtonText}>Cancel</Text>
                            </View>
                        </TouchableHighlight>
                     </View>)
                }
                

                【讨论】:

                  【解决方案19】:

                  实际上,当我使用display: 'none' 或类似下面的东西时,react-native 在 iOS 开发中:

                  const styles = StyleSheet.create({
                    disappearImage: {
                      width: 0,
                      height: 0
                    }
                  });
                  

                  iOS 不会加载 Image 组件的任何其他内容,例如 onLoad 等,因此我决定使用以下内容:

                  const styles = StyleSheet.create({
                    disappearImage: {
                      width: 1,
                      height: 1,
                      position: 'absolute',
                      top: -9000,
                      opacity: 0
                    }
                  });
                  

                  【讨论】:

                    【解决方案20】:

                    如果你想隐藏它但保持组件占用的空间,如组件样式opacity: 0 中的 css 设置 opacity: 0 应该可以解决问题。

                    根据组件的不同,可能需要其他步骤来禁用该功能,因为可以与不可见的项目进行交互。

                    【讨论】:

                      【解决方案21】:

                      三种显示\隐藏组件的方式:

                      - 类组件:/ ---------------------------------------- -------------------------------------------------- -------------------

                      在我使用以下状态的所有示例中:

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

                      1.使用displayprop

                      <View display={this.state.showComponent ? 'flex' : 'none'} /> 
                      

                      2。使用 display 属性和 style

                      <View style={{display:this.state.showComponent ? 'flex' : 'none'}} />
                      

                      3。限制渲染

                      {
                          this.state.showComponent &&
                          <View /> // Or <View> ... </View>
                      }
                      


                      - 功能组件:/ ---------------------------------------- -------------------------------------------------- -------------------

                      在我使用以下状态的所有示例中:

                      const [showComponent, setShowComponent] = useState(true);
                      

                      1.使用display prop

                      <View display={showComponent ? 'flex' : 'none'} /> 
                      

                      2。使用 display 属性和 style

                      <View style={{showComponent  ? 'flex' : 'none'}} />
                      

                      3。限制渲染

                      {
                          showComponent &&
                          <View /> // Or <View> ... </View>
                      }
                      

                      【讨论】:

                        【解决方案22】:

                        非常简单。只需更改为 () => this.showCancel() 如下所示:

                        <TextInput
                                onFocus={() => this.showCancel() }
                                onChangeText={(text) => this.doSearch({input: text})} />
                        
                        <TouchableHighlight 
                            onPress={this.hideCancel()}>
                            <View>
                                <Text style={styles.cancelButtonText}>Cancel</Text>
                            </View>
                        </TouchableHighlight>
                        

                        【讨论】:

                          【解决方案23】:

                          在 react native 中显示或隐藏组件的唯一方法是检查应用状态参数的值,例如 stateprops。我提供了一个完整的例子如下:

                          import React, {Component} from 'react';
                          import {View,Text,TextInput,TouchableHighlight} from 'react-native'
                          
                          class App extends Component {
                          
                              constructor(props){
                                  super(props);
                                  this.state={
                                      show:false
                                  }
                          }
                          
                              showCancel=()=>{
                                  this.setState({show:true})
                              };
                          
                              hideCancel=()=>{
                                  this.setState({show:false})
                              };
                          
                              renderTouchableHighlight(){
                                  if(this.state.show){
                                     return(
                                         <TouchableHighlight
                                             style={{borderColor:'black',borderWidth:1,marginTop:20}}
                                             onPress={this.hideCancel}>
                                             <View>
                                                 <Text>Cancel</Text>
                                             </View>
                                         </TouchableHighlight>
                                     )
                                  }
                                  return null;
                              }
                          
                              render() {
                          
                          
                                  return (
                                      <View style={{justifyContent:'center',alignItems:'center',flex:1}}>
                                          <TextInput
                                              style={{borderColor:'black',borderBottomWidth:1}}
                                              onFocus={this.showCancel}
                                          />
                                          {this.renderTouchableHighlight()}
                          
                                      </View>
                                  );
                              }
                          }
                          
                          export default App;
                          

                          【讨论】:

                            【解决方案24】:

                            您可以使用条件来显示和隐藏组件

                            constructor(){
                            
                                super();
                            
                                this.state ={
                            
                                  isVisible:true
                            
                                }
                              }
                            
                              ToggleFunction = () => {
                            
                                this.setState(state => ({
                            
                                  isVisible: !state.isVisible
                            
                                }));
                            
                              };
                            
                              render() {
                              
                                return (
                            
                                  <View style={styles.MainContainer}>
                            
                                  {
                            
                                    this.state.isVisible ? <Text style= {{ fontSize: 20, color: "red", textAlign: 'center' }}> Hello World! </Text> : null
                                  }
                            
                                  <Button title="Toggle Visibility" onPress={this.ToggleFunction} />
                            
                                  </View>
                                );
                              }
                            

                            【讨论】:

                              【解决方案25】:

                              我这样解决这个问题:

                              &lt;View style={{ display: stateLoad ? 'none' : undefined }} /&gt;

                              【讨论】:

                                【解决方案26】:

                                只是简单地使用它,因为我想使用“useRef”条件对我来说不是一个选项。当你想使用 useRef 钩子并按下按钮时,你可以使用这个假设。

                                   <Button
                                      ref={uploadbtn}
                                      buttonStyle={{ width: 0, height: 0, opacity: 0, display: "none" }}
                                      onPress={pickImage}
                                    />
                                

                                【讨论】:

                                  【解决方案27】:

                                  我们现在有钩子,所以我建议重新格式化。使用钩子打开/关闭组件。

                                  const [modalVisible, setModalVisible] = setState(false);

                                  然后有一个按钮

                                  <Button title="Press Me" onPress={() => {
                                     setModalVisible(true);
                                  }}
                                  

                                  然后,在您的退货声明中

                                  return(
                                  <View>
                                      {modalVisible &&
                                     Insert modal code in here.
                                  }
                                  </View>
                                  )
                                  

                                  【讨论】:

                                    【解决方案28】:

                                    我通常使用这样的东西

                                    const [setShowComponent, showComponent] = useState(false)
                                    return(
                                        <div>
                                             {showComponent && (<Text>Hello</Text>)}
                                             <Button onPress={() => {setShowComponent(true)}}>Click me</Button>
                                        </div>
                                    )
                                    

                                    一旦按下按钮,它将显示“Hello”。这称为条件渲染。条件渲染可以参考w3schools

                                    【讨论】:

                                      【解决方案29】:
                                      checkincheckout = () => {
                                              this.setState({ visible: !this.state.visible })
                                      }
                                      
                                      render() {
                                              return (
                                      {this.state.visible == false ?
                                              <View style={{ alignItems: 'center', flexDirection: 'row', marginTop: 50 }}>
                                      
                                              <View style={{ flex: 1, alignItems: 'center', flexDirection: 'column' }}>
                                      
                                                  <TouchableOpacity onPress={() => this.checkincheckout()}>
                                      
                                                      <Text style={{ color: 'white' }}>Click to Check in</Text>
                                      
                                                  </TouchableOpacity>
                                      
                                              </View>
                                      
                                          </View>
                                      :
                                      <View style={{ alignItems: 'center', flexDirection: 'row', marginTop: 50 }}>
                                      
                                      <View style={{ flex: 1, alignItems: 'center', flexDirection: 'column' }}>
                                      
                                         <TouchableOpacity onPress={() => this.checkincheckout()}>
                                      
                                              <Text style={{ color: 'white' }}>Click to Check out</Text>
                                      
                                          </TouchableOpacity>
                                      
                                      </View>
                                      
                                      </View>
                                       }
                                      
                                      );
                                      }
                                      

                                      仅此而已。享受你的编码......

                                      【讨论】:

                                        猜你喜欢
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 2021-05-07
                                        • 2021-03-27
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 2018-01-09
                                        • 2022-07-21
                                        相关资源
                                        最近更新 更多