我有一个用例,我需要在一个列表中使用多个复选框
一次只能选中一个复选框
。如果我选择Checkbox 1
,然后点击,点击在Checkbox 2
-然后我需要工具关闭Checkbox 1
as I toolonCheckbox 2
请在CODESANDBOX查看代码
我已经为上下文添加了父组件,我希望这将是可修复的。
请帮我解决这个问题
谢谢
好的,这是有点困难没有良好的演示代码都在一个地方或一个codesandbox,这里是一个小得多的演示使用更小和更简单的对象。如果你选中了一个复选框,其余的就变为未选中。您可以看到我是如何在子组件中绑定状态,然后父组件相应地更新状态的。你可以把它放到除了react和typescript之外没有任何依赖关系的代码沙箱中。
完整演示:https://codesandbox.io/s/checkbox-exclusive-lf2vz9
import { useState } from "react";
import "./styles.css";
const AnimalArray = [
{
name: "Bear",
selected: false
},
{
name: "Cat",
selected: false
},
{
name: "Dog",
selected: true
}
];
type Animal = {
name: string;
selected: boolean;
};
type Animals = {
animalList: Array<Animal>;
};
type AnimalProps = {
animal: Animal;
onSelectedChanged: (animal: Animal) => void;
};
const AnimalComponent = (props: AnimalProps) => {
return (
<div>
<input type="text" value={props.animal.name} readOnly={true} />
<input
type="checkbox"
checked={props.animal.selected}
onChange={(el) => {
props.onSelectedChanged({
name: props.animal.name,
selected: el.target.checked
});
}}
/>
</div>
);
};
const AnimalListComponent = (props: Animals) => {
// this could be further pushed up state instead of (or in addition to) being handled here
const [animals, setAnimals] = useState<Animal[]>(props.animalList);
const onChange = (currentAnimal: Animal) => {
setAnimals((currentState) =>
currentState.map((i: Animal) =>
i.name === currentAnimal.name
? {
...i,
selected: currentAnimal.selected
}
: {
...i,
selected: currentAnimal.selected ? false : i.selected
}
)
);
};
return (
<>
<p>list</p>
{animals.map((animal, index) => (
<AnimalComponent
key={index}
onSelectedChanged={onChange}
animal={animal}
/>
))}
</>
);
};
export default function App() {
const [animals] = useState<Animals>({ animalList: AnimalArray });
return (
<div className="App">
<AnimalListComponent animalList={animals.animalList} />
</div>
);
}