我对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/ hideccancel中。 此外,我如何从一开始就隐藏按钮?


当前回答

我会这样做:

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

});

其他回答

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

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;

我通常用这样的东西

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

一旦按下按钮,它就会显示“Hello”。这被称为条件渲染。您可以参考w3schools来了解条件呈现。

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

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

NPM install——save react-native- hidden -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;

你可以使用useState Hook来实现

The useState basically, is a feature which helps us preserve the values of variables even after multiple re-renders.

它充当本地状态管理工具,用于在组件呈现或重新呈现后存储值。

除此之外,你还可以通过改变状态变量的值来触发它来更新UI。

const [show,setShow] = useState(true)

这里我们解构了useState发送的值,第一个是变量,通过它我们可以得到值,第二个是一个函数,通过它我们可以更新状态变量的值。

所以,在你的情况下-

import React, {useState} from 'react';
import { Text, View, StyleSheet,Button } from 'react-native';
import Constants from 'expo-constants';

export default function App() {
const [show,setShow] = useState(true)
return (
 <View style={styles.container}>
   {show && <Text style={styles.paragraph}>
     Showing and Hiding using useState
   </Text>}
    <Button
     title="Press me"
     onPress={() => {setShow(!show)}}
   />
 </View>
);
}

const styles = StyleSheet.create({
container: {
 flex: 1,
 justifyContent: 'center',
 paddingTop: Constants.statusBarHeight,
 backgroundColor: '#ecf0f1',
 padding: 8,
},
paragraph: {
 margin: 24,
 fontSize: 18,
 fontWeight: 'bold',
 textAlign: 'center',
},
});

在本例中,在Button press上,我们将状态变量从true切换为false。

您可以使用布尔条件显示或隐藏JSX Code,我们在这条语句中就是这样做的。

{show && <Text style={styles.paragraph}>
     Showing and Hiding using useState
   </Text>}

这是一种将状态用于UI操作的快速而有效的方法。

隐藏并显示活动指示器的父视图

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

在按钮上按下设置状态如下所示

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

当你需要躲藏的时候

this.setState({isHidden: false})