所以,问题是每当我按下删除按钮时,它只会删除最后一个输入和按钮,而不管索引如何。我尝试将键更改为
key={${index}${name}} ,但这样做效果不太好,因为输入(在主代码中)是可变的,这使事情变得混乱了。
怎样才能根据索引正确地执行删除操作呢?
function App() {
const [names, setNames] = React.useState(["First", "Second",'third','fourth']);
const onNameDelete = useCallback((index: number) => {
setNames((prev) => {
const name = names[index];
return prev.filter(x => x != name);
});
}, [names]);
return (
<div>
{names.map((name, index) => (
<Child
key={index}
name={name}
index={index}
onDelete={onNameDelete}
/>
))}
</div>
);
}
interface ChildProps {
name: string;
index: number;
onDelete: (index: number) => void;
}
export const Child: React.FC<ChildProps> = React.memo(
({ name, index, onDelete }) => {
return (
<div>
<input
defaultValue={name}
/>
<button onClick={() => onDelete(index)}>delete</button>
</div>
);
}