我正在尝试制作一张可以编辑营业时间的表格。我正在使用Switch
中的react-switch
组件,并映射到一周中的每一天。问题在于,每次单击一个switch
元素时,所有switch元素都在更新,但是,我只希望单击的那个元素进行更新。
react-switch文档需要一个onChange
和一个checked
道具,看来我无法通过onClick
。
这是我要渲染的元素:
import Switch from "react-switch";
import { regularHours }from '../../../helpers/momentFunctions';
import { FormGroup, Input } from "reactstrap";
import { Styles } from './Styles/EditDaysOfWeekStyles';
export const EditDaysOfWeek = () => {
const [checked, setChecked] = useState(true);
const handleChange = () => {
setChecked(!checked);
}
return (
<div>
{regularHours.map(({ i, day }) => (
<Styles>
<div key={i}>{day}</div>
<FormGroup key={i}>
<Input type="text" placeholder="8:00AM" />
</FormGroup>
<p>-</p>
<FormGroup key={i}>
<Input type="text" placeholder="8:00PM" />
</FormGroup>
<Switch
checked={checked}
onChange={handleChange}
defaultValue={true}
onColor="#2bbbae"
offColor="#f15a29"
/>
</Styles>
))}
</div>
);
};
这是数据结构:
export const sunday = moment.weekdays(0);
export const monday = moment.weekdays(1);
export const tuesday = moment.weekdays(2);
export const wednesday = moment.weekdays(3);
export const thursday = moment.weekdays(4);
export const friday = moment.weekdays(5);
export const saturday = moment.weekdays(6);
export const regularHours = [
{
day: sunday,
index: 0,
},
{
day: monday,
index: 1,
},
{
day: tuesday,
index: 2,
},
{
day: wednesday,
index: 3,
},
{
day: thursday,
index: 4,
},
{
day: friday,
index: 5,
},
{
day: saturday,
index: 6,
}
];
如果您需要全景视图-我制作了一个沙盒供您玩: https://codesandbox.io/s/dank-leftpad-lt7y2?fontsize=14&hidenavigation=1&theme=dark