【问题标题】:How do I pass dynamic props to class in react-native?如何在 react-native 中将动态道具传递给类?
【发布时间】:2018-08-16 00:39:33
【问题描述】:

我有一个名为 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>
    );
}

【问题讨论】:

  • 您为什么要比较toString 而不仅仅是== false!this.state.valid
  • render() 函数运行时,您确定this.state.value 为真吗?也许它稍后会设置,当您单击图标时,您会在控制台中得到正确的东西,但是当图标被渲染时,它还没有准备好?
  • 查看更新@matejcik
  • @Li357 这是一个很好的电话,我为了性能修复了这个问题,但请检查更新,因为我的问题与此无关。
  • 我不明白为什么代码会到达 return 语句并返回 undefined 而不是颜色。无论如何,既然您还想在onPress 处理程序中更新它,为什么不尝试将颜色设置为状态值并在render() 函数中使用它?

标签: reactjs react-native


【解决方案1】:

也许你可以声明一个局部变量 iconColor 并将 iconColor 值分配给 Icon 的 color 属性。

render(){
   let iconColor  = this.color() || "#000000";
   return(
      <View style={{ alignItems: 'flex-end', padding:10 }}>
          <Icon
            color={iconColor}
          />
      </View>
    )
 }

【讨论】:

  • 您的条件表达式导致this.color 被调用了两次。为什么不this.color() || "#000000"
  • @Li357 是的,我们也可以这样做。感谢您的建议。
【解决方案2】:

函数返回 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"
  }
}

有关工作示例,请参阅 this snack

【讨论】:

    猜你喜欢
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    • 2017-02-23
    • 2021-09-16
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多