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

Cry*_*fel 122 javascript react-native

我是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>
Run Code Online (Sandbox Code Playgroud)

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

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

May*_*tel 125

我会做这样的事情:

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

});
Run Code Online (Sandbox Code Playgroud)

  • 你也可以做`{someBoolVal && <Component />}`,它只会显示bool值是否为真. (21认同)
  • 仅在将“ return”更改为“ return null”之后为我工作 (3认同)
  • 我不知道这是接受的答案,没有实现原始所需的功能显示/隐藏,而是添加/删除 (3认同)

Kri*_*pta 121

在你的渲染功能:

{ this.state.showTheThing && 
  <TextInput/>
}
Run Code Online (Sandbox Code Playgroud)

然后就做:

this.setState({showTheThing: true})  // to show it  
this.setState({showTheThing: false}) // to hide it
Run Code Online (Sandbox Code Playgroud)

  • 也许这有效?因为逻辑上的 `&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;)}` (3认同)
  • 这对我有用。但是,我不确定为什么当我执行类似 `{ this.state.showTheThing &amp;&amp; (&lt;Text&gt;foo&lt;/Text&gt; &amp;&amp; &lt;Text&gt;bar&lt;/Text&gt;)}` 时,只显示“bar”用户界面。我希望会显示“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;}` (2认同)

Raj*_*shu 43

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

View.hide = true or parentView.addSubView(childView)
Run Code Online (Sandbox Code Playgroud)

但是反应原生工作的方式完全不同.实现此类功能的唯一方法是将您的组件包含在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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

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

renderIf(predicate)(element)
Run Code Online (Sandbox Code Playgroud)

renderif.js

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

  • 如果您需要保持状态,这将不起作用,删除元素重置他的状态。所以每次你再次渲染就像你再次创建组件一样。 (2认同)

小智 16

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

render(){
    return({yourCondition ? <yourComponent /> : null});
}
Run Code Online (Sandbox Code Playgroud)

  • 第2行应该要求括号. (3认同)

mau*_*n85 12

我需要在两个图像之间切换.通过它们之间的条件切换,有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>
Run Code Online (Sandbox Code Playgroud)

样式:

var styles = StyleSheet.create({
  logo: {
    width: 200,
    height: 200,
  },
  hidden: {
    width: 0,
    height: 0,
  },
});
Run Code Online (Sandbox Code Playgroud)

截屏

  • 当您尝试创建动画微调器时,这些示例中的任何一个都无法正常工作.就像我在回答android中试图为动画gif切换img时所提到的那样,当没有显示png和gif时会导致5s延迟.我认为延迟是由将gif加载到内存中引起的,这可能需要一些时间.然而iOS似乎在这里做得更好.如果您不相信我,请亲自尝试. (3认同)

小智 11

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

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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

如果你对编程很陌生,那么这一行对你来说一定很奇怪:

{this.state.isHidden ? <ToHideAndShowComponent/> : null}
Run Code Online (Sandbox Code Playgroud)

这条线相当于

if (this.state.isHidden)
{
  return ( <ToHideAndShowComponent/> );
}
else
{
  return null;
}
Run Code Online (Sandbox Code Playgroud)

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

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

问候,


Har*_*nda 10

在此输入图像描述

隐藏显示父视图Activity Indicator

constructor(props) {
  super(props)

  this.state = {
    isHidden: false
  }  
} 
Run Code Online (Sandbox Code Playgroud)

隐藏显示为关注

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

完整参考

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>
   );
}
Run Code Online (Sandbox Code Playgroud)

按钮按下设置状态如下

onSignupPress() {
  this.setState({isHidden: true})
}
Run Code Online (Sandbox Code Playgroud)

当你需要隐藏

this.setState({isHidden: false})
Run Code Online (Sandbox Code Playgroud)


小智 8

只是用

style={ width:0, height:0 } // to hide
Run Code Online (Sandbox Code Playgroud)

  • 如何将元素恢复到原始宽度和高度? (5认同)
  • 如果您在答案中添加一些上下文/细节会很有帮助. (4认同)
  • 不明白为什么这会被贬低,但在很多情况下这是好建议.我需要在动画和非动画gif之间切换.条件切换img导致延迟,屏幕上没有img.作为修复的一部分,我正在显示两个img,但应隐藏的那个没有宽度和高度. (4认同)

Est*_*cas 8

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

<View style={{display: 'none'}}> </View>
Run Code Online (Sandbox Code Playgroud)

  • 小心不要将其与“position:absolute”一起使用,它实际上并没有隐藏它!0.54 - 0.59 的已知错误(至少):https://github.com/facebook/react-native/issues/18415 (3认同)

Ton*_*thy 6

我有同样的问题,我想要显示/隐藏视图,但我真的不希望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;
Run Code Online (Sandbox Code Playgroud)


d4v*_*idi 6

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

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

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

  • 这个想法适合我,谢谢.如果有人需要,也请看一下:https://gist.github.com/jaysoo/cbb81a07cc22015a72e9 (2认同)

Shi*_*m 0 6

constructor(props) {
    super(props);
    this.state = {
      visible: true,
}
}
Run Code Online (Sandbox Code Playgroud)

声明可见假所以默认模式/视图是隐藏的

示例 = () => {

 this.setState({ visible: !this.state.visible })
Run Code Online (Sandbox Code Playgroud)

}

**函数调用**

{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> 
 }
Run Code Online (Sandbox Code Playgroud)


Ara*_*esi 6

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

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

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

.  
...
constructor(props) {
super(props);
this.state = {showComponent: true};
}
Run Code Online (Sandbox Code Playgroud)

1.使用display道具

<View display={this.state.showComponent ? 'flex' : 'none'} /> 
Run Code Online (Sandbox Code Playgroud)

2. 使用display道具style

<View style={{display:this.state.showComponent ? 'flex' : 'none'}} />
Run Code Online (Sandbox Code Playgroud)

3.限制渲染

{
    this.state.showComponent &&
    <View /> // Or <View> ... </View>
}
Run Code Online (Sandbox Code Playgroud)

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

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

const [showComponent, setShowComponent] = useState(true);
Run Code Online (Sandbox Code Playgroud)

1.使用display道具

<View display={showComponent ? 'flex' : 'none'} /> 
Run Code Online (Sandbox Code Playgroud)

2. 使用display道具style

<View style={{showComponent  ? 'flex' : 'none'}} />
Run Code Online (Sandbox Code Playgroud)

3.限制渲染

{
    showComponent &&
    <View /> // Or <View> ... </View>
}
Run Code Online (Sandbox Code Playgroud)


yka*_*ica 5

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

//in constructor    
this.state = {opacity: 100}

/in component
style = {{opacity: this.state.opacity}}

//when you want to hide
this.setState({opacity: 0})
Run Code Online (Sandbox Code Playgroud)