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


当前回答

只使用

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

其他回答

你可以使用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操作的快速而有效的方法。

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

大多数时候我是这样做的:

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 && <ToHideAndShowComponent/>}。这里,左操作数在右操作数之前求值,因此如果isHidden为false,则该组件将不显示。

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

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

下面的例子是用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>
  ......

}