React Native中能否使用函数返回值替代颜色名设置背景色
问题原因与修复方案
核心问题点
- 你定义的
fun()方法没有显式返回值,调用时默认返回undefined,这是backgroundColor属性取值异常的直接原因 - 直接对
this.state.maincolor赋值的写法不符合React规范:修改state必须调用this.setState(),否则不会触发组件重渲染,视图也不会响应状态变化 - 你当前的需求是根据props的counter值动态返回颜色,不需要额外把颜色存入state,直接让方法返回对应颜色值即可,也可以避开三元运算符的写法
轻量修复方案(无需额外存储颜色到state)
class counterApp extends Component { // 直接根据counter返回对应颜色 getBgColor() { if (this.props.counter === 0) { return dark.bg } return light.bg } render() { return ( <View style={{ justifyContent: 'center', alignItems: 'center', top: '45%', backgroundColor: this.getBgColor() }}> {/* 其余视图内容 */} </View> ) } }
需存储颜色到state的兼容方案
如果后续有其他逻辑需要把颜色存入state,可以监听counter的变化触发state更新:
class counterApp extends Component { state = { maincolor: '' } componentDidUpdate(prevProps) { // counter值变化时更新对应颜色 if (prevProps.counter !== this.props.counter) { let targetColor = light.bg if (this.props.counter === 0) { targetColor = dark.bg } this.setState({ maincolor: targetColor }) } } render() { return ( <View style={{ justifyContent: 'center', alignItems: 'center', top: '45%', backgroundColor: this.state.maincolor }}> {/* 其余视图内容 */} </View> ) } }
内容的提问来源于stack exchange,提问作者Chaudhary Ahmad
相关产品推荐
相关产品推荐

