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


当前回答

您可以使用这些条件来显示和隐藏组件

constructor(){

    super();

    this.state ={

      isVisible:true

    }
  }

  ToggleFunction = () => {

    this.setState(state => ({

      isVisible: !state.isVisible

    }));

  };

  render() {
  
    return (

      <View style={styles.MainContainer}>

      {

        this.state.isVisible ? <Text style= {{ fontSize: 20, color: "red", textAlign: 'center' }}> Hello World! </Text> : null
      }

      <Button title="Toggle Visibility" onPress={this.ToggleFunction} />

      </View>
    );
  }

其他回答

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

实际上,在iOS开发中,通过react-native,当我使用display: 'none'或如下所示:

const styles = StyleSheet.create({
  disappearImage: {
    width: 0,
    height: 0
  }
});

iOS不加载任何其他的图像组件,如onLoad或等,所以我决定使用如下:

const styles = StyleSheet.create({
  disappearImage: {
    width: 1,
    height: 1,
    position: 'absolute',
    top: -9000,
    opacity: 0
  }
});
// 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)}}/>

我们现在有钩子,所以我建议重新格式化。使用钩子打开/关闭组件。

const [modalVisible, setModalVisible] = setState(false);

然后有一个按钮

<Button title="Press Me" onPress={() => {
   setModalVisible(true);
}}

然后,在return语句中

return(
<View>
    {modalVisible &&
   Insert modal code in here.
}
</View>
)

只使用

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