【问题标题】:Redux state value used as a style property value?Redux 状态值用作样式属性值?
【发布时间】:2018-08-24 15:39:11
【问题描述】:

我正在使用 redux 来存储像 (#000000) 这样的十六进制颜色值。我有许多按钮调度一个动作,该动作是按钮颜色的值(红色按钮调度红色)我的组件现在可以访问状态,但是当我使用该状态来设置背景颜色的样式时,我得到一个未定义的错误!我的组件确实在文本标记中呈现值,所以我知道它返回了正确的十六进制值。我唯一能想到的可能是因为它不是字符串包装器?我试过这样做:

const primaryColor = this.props.theme;

const styles = {
  backgroundColor: primaryColor
}

我收到错误:无法读取未定义的属性“主题”

这是我的 Theme.js 文件:

class Themes extends Component {

  render() {
    return (
      <View style={styles.container}>
        <Text>{this.props.theme}</Text>
        <Button onPress={() => 
this.props.themeColorValue('#3498db')}>Blue</Button>
        <Button onPress={() => 
this.props.themeColorValue('#e67e22')}>Orange</Button>
        <Button onPress={() => 
this.props.themeColorValue('#9b59b6')}>Purple</Button>
      </View>

   );
  }
}

const primaryColor = this.props.theme;

const styles = {
  container: {
    backgroundColor: primaryColor,
    flex: 1,
    paddingHorizontal: 10,
    paddingVertical: 10,
    flexDirection: 'column',
    justifyContent: 'space-between',
  },

};


function mapStateToProps(state) {
  return {
    theme: state.themeColorValue,
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ themeColorValue: themeColorValue }, dispatch)
}

export default connect(mapStateToProps, mapDispatchToProps)(Themes);

感谢任何可以帮助我解决此问题的人,干杯。

【问题讨论】:

  • 我可以看看你的渲染方法吗?另外,你是如何更新 state.theme 的?因为如果你使用 redux,颜色应该已经通过 props (mapStateToProps)
  • 嗨古斯塔沃。我刚刚在我的帖子中添加了我的渲染方法。我也在使用 mapStateToProps。如果您查看 标记,当我单击每个按钮时正在输出正确的值,这就是我知道我的状态正在正确传递给我的组件的方式。感谢您查看此内容!
  • 您在渲染方法中使用 this.props,在第一个代码 sn-p 中使用 this.state。你在哪里使用 setState 将主题值保存到组件状态中?
  • 抱歉 Josh 很好,我刚刚修正了它,这是我的错字!
  • 在哪里?在构造函数中?在特定的生命周期方法中?请具体说明:)

标签: reactjs redux styles native


【解决方案1】:
const primaryColor = this.props.theme;

const styles = {
  container: {
    backgroundColor: primaryColor,
    flex: 1,
    paddingHorizontal: 10,
    paddingVertical: 10,
    flexDirection: 'column',
    justifyContent: 'space-between',
  },

};

将此部分移动到渲染函数的开头,然后您的代码应该可以工作。

【讨论】:

  • 成功了,谢谢本杰明!约书亚,你也在这方面走上正轨。干杯!
  • 没问题。我很乐意提供帮助。
  • 另一个问题。通过在每个大约 6 的组件上执行此操作,我的应用程序会减慢很多吗? (通过在渲染方法中使用我的样式对象并将 mapStateToProps 其他 redux 功能应用于每个组件?
  • 我觉得对速度影响不大。看起来大多数样式都是不变的,你可以把它放在一个 css 文件中,只改变内联的颜色。
猜你喜欢
  • 2019-01-28
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 2016-11-12
  • 2023-03-14
  • 2019-12-07
  • 1970-01-01
相关资源
最近更新 更多