我有 8 <TouchableWithoutFeedback>
网格形式的元素。它们不使用 map 动态呈现。
this.props.selectCell('rain')}>
<TouchableWithoutFeedback onPress={()=>this.props.selectCell('rain')}>
<Row style={[styles.orangish,styles.cell]}>
<Image source={Rain} />
</Row>
</TouchableWithoutFeedback>
想法是选择一个onPress。
Action
export const selectCell = (cellId) => {
console.log(cellId);
return {
type: 'select_cell',
payload: cellId
};
}
reducer
export default (state= {}, action) => {
switch(action.type) {
case 'select_cell': {
//trying to figure out what to do here
}
};
1) 如何在 reducer 中切换选择?
2) 如何根据状态渲染新图像?
最佳答案
在reducer状态下有一个selectedCellId属性,设置如下:
export default (state= {}, action) => {
switch(action.type) {
case 'select_cell': {
return {
...state,
selectedCellId: action.payload
};
}
};
另一种方法是将 8 个单元格设置为 selected = false。
const defaultState = {
cells: [
{ selected: false },
{ selected: false },
{ selected: false },
{ selected: false },
{ selected: false },
{ selected: false },
{ selected: false },
{ selected: false }
]
};
然后在reducer中,
export default (state= defaultState, action) => {
switch(action.type) {
case 'select_cell': {
let { cells } = state;
cells = cells.slice();
cells[action.payload] = { selected: true };
return {
...state,
cells
};
}
};
如果您已命名单元格,则将单元格集合设为对象映射而不是数组。
关于javascript - React-native:使用 redux 处理多个元素选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48483809/