要保存选中的选项,您可以使用React-Redux来管理应用程序的状态。下面是一个包含代码示例的解决方法:
react-redux
库:npm install react-redux
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import rootReducer from './reducers'; // 导入根reducer
const store = createStore(rootReducer); // 创建store
ReactDOM.render(
,
document.getElementById('root')
);
// reducers.js
const initialState = {
options: [
{ id: 1, text: 'Option 1', selected: false },
{ id: 2, text: 'Option 2', selected: false },
{ id: 3, text: 'Option 3', selected: false },
],
};
const rootReducer = (state = initialState, action) => {
switch (action.type) {
case 'TOGGLE_OPTION':
return {
...state,
options: state.options.map((option) =>
option.id === action.payload
? { ...option, selected: !option.selected }
: option
),
};
default:
return state;
}
};
export default rootReducer;
// actions.js
export const toggleOption = (optionId) => ({
type: 'TOGGLE_OPTION',
payload: optionId,
});
useSelector
和useDispatch
钩子来读取和分发状态。在列表中渲染选项,并在点击时调度切换选项的action。import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { toggleOption } from './actions';
const OptionsList = () => {
const options = useSelector((state) => state.options);
const dispatch = useDispatch();
return (
{options.map((option) => (
- dispatch(toggleOption(option.id))}
style={{ fontWeight: option.selected ? 'bold' : 'normal' }}
>
{option.text}
))}
);
};
export default OptionsList;
通过以上步骤,您现在可以在应用程序中保存选中的选项。每当用户点击选项时,它们的选择状态将切换,并且Redux store中的状态将被更新。
上一篇:保存选择的选项并进行检查