Reactjs 如何在react native中向类传递动态道具?
我有一个名为color的函数,它以字符串的形式返回十六进制颜色。我想将类图标的属性颜色设置为函数颜色的结果。结果是函数返回未定义的,我似乎不知道为什么 我已经验证了if语句是否有效,因此可能是我返回的函数不正确或引用的函数不正确。但是为什么当我将颜色设置为函数的结果时,它不会更新,为什么函数返回未定义Reactjs 如何在react native中向类传递动态道具?,reactjs,react-native,Reactjs,React Native,我有一个名为color的函数,它以字符串的形式返回十六进制颜色。我想将类图标的属性颜色设置为函数颜色的结果。结果是函数返回未定义的,我似乎不知道为什么 我已经验证了if语句是否有效,因此可能是我返回的函数不正确或引用的函数不正确。但是为什么当我将颜色设置为函数的结果时,它不会更新,为什么函数返回未定义 color() { if (this.state.value) { if (this.state.valid) { console.log("*")
color() {
if (this.state.value) {
if (this.state.valid) {
console.log("*")
return "#44c0b9"
} else {
console.log("#")
return "#D3D3D3"
}
}
}
当我运行{this.color()}
时,我会得到*或#,这很好,但是当我运行console.log(this.color())
时,当我想象应该得到返回值时,我会得到未定义的值。然后,当尝试将{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>
);
}
render(){
返回(
this.color()}
/>
);
}
也许您可以声明一个局部变量iconColor,并将iconColor值指定给Icon的颜色属性
render(){
让iconColor=this.color()| |“#000000”;
返回(
)
}
关于函数返回未定义的的唯一方法是不点击任何返回语句
所以我很确定第一个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"
}
}
有关工作示例,请参阅。为什么要将与字符串
进行比较,而不仅仅是==false
或!this.state.valid
?当render()函数运行时,是否确定this.state.value
为真?也许它会在稍后设置,当您单击图标时,您会在控制台中获得正确的内容,但当图标呈现时,它还没有准备好?请查看更新@matejcik@Li357这是一个很好的电话,我为了表现而修正了它,但是签出更新,因为我的问题与此无关。我不明白为什么代码会到达return语句并返回undefined
,而不是颜色。无论如何,既然要在onPress
处理程序中更新颜色,为什么不尝试将颜色设置为状态值并在render()
函数中使用它呢?您的条件表达式导致this.color
被调用两次。为什么不this.color()| |“#000000”
?@Li357是的,我们也可以这样做。谢谢你的建议。