【发布时间】: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