最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to toggle boolean state in React and TypeScript? - Stack Overflow

programmeradmin2浏览0评论

I am new to React and TypeScript.

I want to toggle a boolean state (true/false) with a handler function. I've read other posts about how to do this in ES6 but I am unclear of how to achieve this in TypeScript.

So far I have:

  const MyComponent = () => {
    const [collapseUpper, setCollapseUpper] = React.useState(true);

    const handleCollapse = () => {
      collapseUpper = !setCollapseUpper;
    };

    return (
       <Link onClick={handleCollapse}>More</Link>
       <Collapse in={collapseUpper}>
         //content

But I cannot get it to work.

Can anyone point me in the right direction?

I am new to React and TypeScript.

I want to toggle a boolean state (true/false) with a handler function. I've read other posts about how to do this in ES6 but I am unclear of how to achieve this in TypeScript.

So far I have:

  const MyComponent = () => {
    const [collapseUpper, setCollapseUpper] = React.useState(true);

    const handleCollapse = () => {
      collapseUpper = !setCollapseUpper;
    };

    return (
       <Link onClick={handleCollapse}>More</Link>
       <Collapse in={collapseUpper}>
         //content

But I cannot get it to work.

Can anyone point me in the right direction?

Share Improve this question edited Jun 17, 2020 at 4:59 wentjun 42.6k10 gold badges107 silver badges113 bronze badges asked Jun 17, 2020 at 4:38 MeltingDogMeltingDog 15.5k52 gold badges178 silver badges322 bronze badges 3
  • 1 setCollapseUpper is a function not a value – Code Maniac Commented Jun 17, 2020 at 4:39
  • You need to invoke it setCollapseUpper(!collapseUpper) – Code Maniac Commented Jun 17, 2020 at 4:40
  • Read here reactjs/docs/hooks-reference.html#usestate – Code Maniac Commented Jun 17, 2020 at 4:41
Add a ment  | 

2 Answers 2

Reset to default 6

This is how it should be done:

const handleCollapse = () => {
  setCollapseUpper(!collapseUpper);
};

You will need to call the setCollapseUpper to handle any updates in state.

Better still, you can use the callback function to update the state:

const handleCollapse = () => {
  setCollapseUpper((prevState) => !prevState);
};

you need to change the value of collapseUpper not setCollapseUpper:

const [collapseUpper, setCollapseUpper] = React.useState(true);

const handleCollapse = () => {
  setCollapseUpper(!collapseUpper);
};
发布评论

评论列表(0)

  1. 暂无评论