我使用redux存储十六进制颜色值,如(#000000)。我有很多按钮调度一个动作,它是按钮颜色的值(红色按钮调出红色)我的组件现在可以访问状态,但是当我使用状态来设置backgroundColor的样式时,我得到一个未定义的错误!我的组件确实在文本标记中呈现值,因此我知道它返回正确的十六进制值。我唯一能想到的可能是因为它不是字符串中的包装器?我试过这样做:
const primaryColor = this.props.theme;
const styles = {
backgroundColor: primaryColor
}
我收到错误:无法读取未定义的属性'theme'
这是我的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);
感谢任何能帮我解决这个问题的人,干杯。
答案 0 :(得分:0)
const primaryColor = this.props.theme;
const styles = {
container: {
backgroundColor: primaryColor,
flex: 1,
paddingHorizontal: 10,
paddingVertical: 10,
flexDirection: 'column',
justifyContent: 'space-between',
},
};
将此部分移动到渲染函数的开头,然后您的代码应该可以工作。