首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对象状态使用keyof typeof

对象状态使用keyof typeof
EN

Stack Overflow用户
提问于 2022-10-18 11:17:25
回答 1查看 51关注 0票数 0

键的类型应该是什么?如果我添加(key: string),就会得到一个"string“不能用于索引类型”active1: boolean,active2“的错误。

代码语言:javascript
复制
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>
);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-18 11:22:32

您可以使用keyof typeof activekeyof T,其中T是为该对象状态定义的类型。

代码语言:javascript
复制
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>
    );
}

操场连接

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74110072

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档