reactjs - 如何在 react-native 中将动态道具传递给类?
问题描述
我有一个名为 color 的函数,它以字符串的形式返回一个十六进制颜色。我想将我的类 Icon 的属性颜色设置为函数颜色的结果。结果是该函数返回未定义,我似乎无法弄清楚为什么。
我已经验证 if 语句确实有效,所以我可能错误地返回它或不正确地引用函数。但是为什么当我设置颜色等于函数的结果时它没有更新,为什么函数返回未定义?
color() {
if (this.state.value) {
if (this.state.valid) {
console.log("*")
return "#44c0b9"
} else {
console.log("#")
return "#D3D3D3"
}
}
}
当我运行时,{this.color()}
我得到 * 或 # 这很好,但是当我运行console.log(this.color())
时,当我想我应该得到返回值时,我得到 Undefined。然后,当尝试在{this.color()}
我的类图标中实现时,颜色没有改变,它既不显示函数颜色的颜色,也显示黑色。
render() {
return (
<View style={{ alignItems: 'flex-end', padding:10 }}>
<Icon
raised
reverse
color={this.color()}
name='arrow-right'
type='font-awesome'
onPress={() => this.color()}
/>
</View>
);
}
解决方案
该函数可以返回的唯一方法undefined
是,如果您没有点击任何 return 语句。
所以我很确定第一个if (this.state.value)
没有通过。您的问题与此有关,与其他任何问题无关。试试这个看看发生了什么:
color() {
console.log("calling color, state value is:")
console.log(this.state.value)
if (this.state.value) {
if (this.state.valid) {
console.log("*")
return "#44c0b9"
} else {
console.log("#")
return "#D3D3D3"
}
} else {
console.log("%")
return "#ff0000"
}
}
有关工作示例,请参阅此小吃。
推荐阅读
- python-3.x - 打印dict显示keyerror
- sql-server - 如果变量在 T-SQL 语句的 IN 子句中,如何实现参数化 SQL
- jenkins - 为什么将动态变量作为代码插件注入自定义管道时无法正确解析?
- node.js - React 无法编译 reactLifecyclesCompat 错误
- python-3.x - 3**2+1!=30/3 它给出了 False
- php - 为什么我的while循环似乎总是错误的
- python - 字典理解中的 Lambda
- javascript - 在未启动的 $http.get 请求中无法读取未定义的属性“数据”
- c++ - C ++写入mongo,字符串字段在聚合管道中不起作用
- java - JTextfield 默认操作后 JButton 变为启用状态