键的类型应该是什么?如果我加上(key:string(,我得到一个错误;字符串";不能用于索引类型";active1:布尔值,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>
);
您可以使用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>
);
}
游乐场链接