reactjs - 有条件地为 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;
}}
>
解决方案
您使用的条件将始终返回false
为空字符串不是 undefined :
console.log(undefined == "")
这种行为很奇怪,因为您的函数甚至没有在箭头函数中返回。
以下应该通过放置一个不做任何事情的函数来解决问题:
onPress={description ? this._onPressButton : x => {} }
这也可以与内联一起使用,如果:
onPress={description && this._onPressButton }
推荐阅读
- angular - 来自 JS 的空字符串未绑定到 .Net Core 3.1 Web api 中的可为空 GUID
- c# - 使用 C# Winform 在 Mysql 上的异步问题
- windows - ENSURE 的异常(strDocName.LoadString(AFX_IDS_UNTITLED))
- python - .endswith() 方法引发异常“AttributeError: 'str' object has no attribute 'value'”
- java - springcloud api网关属性文件声明变量
- sql - 如何按子类别和diapazone计算
- elasticsearch - 如何通过 Elasticsearch 中文档数组中对象的多个字段进行查询?
- python - python (Django) 通过在 html 中按 textarea 获取字符串来删除换行符,但答案是错误的。为什么?
- java - 为什么使用静态方法来获取实例而不是构造函数?
- python-3.x - 使用 tkinter 在 MacOS 上提供旋转沙滩球