首页 > 解决方案 > 有条件地为 TouchableHighlight 渲染 onPress

问题描述

我正在尝试有条件地渲染一个onPress,如果描述道具是undefined,我确实想要任何onPress功能。我的 onPress 无论如何都会触发,如果描述未定义,我该如何删除它

constructor(props) {
    super(props);

    this._onPressButton = this._onPressButton.bind(this);
}

_onPressButton(event) {
    Alert.alert(event.description);
}

render() {
    const { start, end, summary, description } = this.props;

    return (
        <TouchableHighlight
            onPress={() => {
                description == "" ? null : this._onPressButton;
            }}

        >

标签: reactjsreact-native

解决方案


您使用的条件将始终返回false为空字符串不是 undefined :

console.log(undefined == "")

这种行为很奇怪,因为您的函数甚至没有在箭头函数中返回。

以下应该通过放置一个不做任何事情的函数来解决问题:

onPress={description ? this._onPressButton : x => {} }

这也可以与内联一起使用,如果:

onPress={description && this._onPressButton }

推荐阅读