键的类型应该是什么?如果我添加(key: string),就会得到一个"string“不能用于索引类型”active1: boolean,active2“的错误。
const [actives, setActives] = React.useState({
active1: false,
active2: false,
});
const toggle = (key) => setActives((actives) => ({ ...actives, [key]: !actives[key] }));
return (
<View>
<Button onPress={() => toggle('active1')} active={actives.active1} />
<Button onPress={() => toggle('active2')} active={actives.active2} />
</View>
);发布于 2022-10-18 11:22:32
您可以使用keyof typeof active或keyof T,其中T是为该对象状态定义的类型。
function Comp () {
const [actives, setActives] = React.useState({
active1: false,
active2: false,
});
const toggle = (key: keyof typeof actives) => setActives((actives) => ({ ...actives, [key]: !actives[key] }));
return (
<div>
<button onClick={() => toggle('active1')} disabled={!actives.active1} />
<button onClick={() => toggle('active2')} disabled={!actives.active2} />
</div>
);
}https://stackoverflow.com/questions/74110072
复制相似问题