【发布时间】:2017-09-13 13:53:36
【问题描述】:
我想在按下按钮时更改整个应用的样式。我想我可以用reducer 做到这一点。所以我创建了:
减速器样式:
const initialState =
{
name: styleNormal,
path: './styles/styleNormal'
}
export default function reducer01 (state = initialState, action) {
switch (action.type) {
case "changeStyleNormal":
return [
...state,
{
name: name: action.payload,
path: './styles/styleNormal'
}
];
case "changeStyleNew":
return [
...state,
{
name: name: action.payload,
path: './styles/styleNew'
}
];
default:
return state
}
}
和行动:
const CHANGE_STYLE_NORMAL = 'changeStyleNormal';
const CHANGE_STYLE_NEW = 'changeStyleNew';
export function changeStyleNormal(style){
return {
type: CHANGE_STYLE_NORMAL,
payload: style
}
}
export function changeStyleNew(style){
return {
type: CHANGE_STYLE_NEW,
payload: style
}
}
我在 styles 文件夹中创建了 2 种样式,因此只能应用 1 种样式,具体取决于从减速器中选择/返回的样式。默认情况下,我在 Reducer initialState 中有 styleNormal。导入了Actions,Reducer合并了mapStateToProps:
function mapStateToProps(state) {
return {
style: state.style
}
}
function mapDispatchToProps(dispatch) {
return {
changeStyleNormal: (style) => {
dispatch(changeStyleNormal(style));
},
changeStyleNew: (style) => {
dispatch(changeStyleNew(style));
}
}
}
添加了 2 个按钮:
<TouchableOpacity
style={styles.clickMe}
onPress={()=>this.props.changeStyleNew('styleNew')}>
<Text style={styles.black18}>New Style</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.clickMe}
onPress={()=>this.props.changeStyleNormal('styleNormal')}>
<Text style={styles.black18}>Normal Style</Text>
</TouchableOpacity>
现在当组件被调用时,
render() {
console.log("style: ",this.props.style);
这给出了样式:
我无法从render() 中访问this.props.style,那么我应该在哪里设置变量style = this.props.style.path?
此外,当我单击任何按钮时,操作都很好,但样式会附加到减速器:
我只希望通过的那个在减速器中。所以我可以用它来设置样式。
这是正确的方法吗?请帮忙。
非常感谢。
更新 1:
class Ext2 extends Component {
//console.log('Style:', this.props.people); // <= This throws an internal server error 500
// const styles = this.props.style.path; // same error as above
render() {
console.log("style: ",this.props.style); //<= Works
console.log("stylePath: ",this.props.style.path) //<= Works
【问题讨论】:
-
可能不相关,但您的初始状态是一个对象,但您从减速器返回一个数组。
标签: reactjs react-native redux react-redux