首页 文章

以原生方式隐藏/显示组件

提问于
浏览
91

我想知道如何隐藏/显示组件 .
这是我的测试用例:

<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 .

我不知道如何"access"组件 TouchableHighlight 组件,以隐藏/显示我的功能 showCancel/hideCancel .
另外,我怎样才能从一开始就隐藏按钮?

15 回答

  • 1

    我会做这样的事情:

    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()}          
            );
        }
    
    });
    
  • 14

    在你的渲染功能:

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

    然后就做:

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

    在反应或反应原生组件隐藏/显示或添加/删除的方式不像在Android或iOS中那样工作 . 我们大多数人都认为会有类似的策略

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

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

    在这个例子中,我将根据按钮单击设置文本视图的可见性 .

    enter image description here

    这个任务背后的想法是创建一个名为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>
        );
      }
    }
    

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

    renderIf(predicate)(element)
    

    renderif.js

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

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

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

    我需要在两个图像之间切换 . 通过它们之间的条件切换,有5秒的延迟,没有显示图像 .

    我正在使用来自downvoted 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,
      },
    });
    

    screencast

  • 2

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

    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条件(例如render函数的return()部分),因此你必须使用这种表示法 .

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

    问候,

  • 9

    另一个选项是应用 absolute positioning via styling ,在屏幕外坐标中设置隐藏组件:

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

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

  • 0

    只是用

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

    我有同样的问题,我想要显示/隐藏视图,但我真的不希望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;
    
  • 7

    enter image description here

    Hide 和_1496626_的父视图 Activity Indicator

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

    HideShow 如下

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

    Full reference

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

    按钮按下设置状态如下

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

    当你需要隐藏

    this.setState({isHidden: false})
    
  • 0

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

  • 5

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

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

    很容易 . 只需更改为()=> 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>
    
  • 40

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

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

    我只是使用下面的方法来隐藏或查看按钮 . 希望它会对你有所帮助 . 只是更新状态和添加隐藏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>)
    }
    

相关问题