首页 > 解决方案 > 如何在 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>
    );
}

标签: reactjsreact-native

解决方案


该函数可以返回的唯一方法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"
  }
}

有关工作示例,请参阅此小吃。


推荐阅读