【问题标题】:Can I use a function instead of color name in react native我可以在本机反应中使用函数而不是颜色名称吗
【发布时间】:2021-07-30 12:03:36
【问题描述】:

我使用 redux 创建了一个计数器应用程序我想在值为 0 时更改颜色,并在值为 1 时再次更改。我为此创建了一个函数,当我使用 console.log 它显示正确的颜色名称但是当我以显示未定义的背景颜色名称调用函数时,它不显示。 (我不想为此使用三元运算符)

class counterApp extends Component {

    state={
        maincolor: '',
    }

    
    fun(){
        
        if (this.props.counter == 0) {
            this.state.maincolor = dark.bg
            
        }
        else {
            this.state.maincolor = light.bg
            
        }
    }

    render() {
        return (
            <View style={{ 
                  justifyContent: 'center', 
                  alignItems: 'center', top: '45%', 
                  backgroundColor: this.fun()
                
             }}>

【问题讨论】:

  • 尝试在函数中添加return? fun () { if (this.props.counter == 0) { return dark.bg } }
  • 这与python 标签有什么关系?
  • 您对此有什么问题吗?

标签: reactjs react-native react-redux react-native-stylesheet


【解决方案1】:

你的函数什么都不返回!所以这就是你得到undefined的原因 你必须在fun()返回颜色

fun(){
    if (this.props.counter == 0) return dark.bg;
    return light.bg;
}

您也不能直接设置状态值 (React docs),而应使用 setState
在这个例子中,你可以这样做

fun() {
    if (this.props.counter == 0) this.setState({ maincolor: dark.bg });
    else this.setState({ maincolor: light.bg});
}

现在,在某处致电fun()(例如componentDidMountconstructor),
并在渲染中使用它

render() {
    return (
        <View style={{ justifyContent: 'center', alignItems: 'center', top: '45%', 
            backgroundColor: this.state.maincolor
            
         }}>
    )
}

【讨论】:

  • 非常感谢您。它可以工作,但是当我刷新时,它会更新,否则它只需要第一个值。是否可以根据值的变化来更新值?
猜你喜欢
  • 2021-11-25
  • 2012-03-25
  • 1970-01-01
  • 2021-06-21
  • 2020-03-27
  • 1970-01-01
  • 1970-01-01
  • 2019-01-10
  • 1970-01-01
相关资源
最近更新 更多