我想在按下按鈕時更改整個應用程序的樣式。我以爲我可以用reducer
來做到這一點。因此,我創建:更改樣式onPress + Redux
ReducerStyles:
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
}
}
我創建了2款在styles
文件夾,以便只有1可以根據一個選擇的應用/從返回減速器。默認情況下,我在Reducer initialState
中有styleNormal
。進口的操作,減速組合後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
可能不相關,但你的初始狀態是一個對象,但你從還原器返回一個數組。 –