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


当前回答

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

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

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

其他回答

显示\hide组件的三种方法:

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

在我使用的所有例子中,如下所示:

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

1. 使用展示道具

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

2. 使用有风格的显示道具

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

3.限制呈现

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


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

在我使用的所有例子中,如下所示:

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

1. 使用展示道具

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

2. 使用有风格的显示道具

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

3.限制呈现

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

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

}

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

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

在你的渲染函数中:

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

然后就这样做:

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

我需要在两幅图像之间切换。在它们之间进行条件切换时,有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,
  },
});