用打字稿反应useState(仅一个变量)

时间:2019-12-04 13:44:21

标签: reactjs typescript

我以reactjs.org为例:

function Example() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

现在我想用打字稿扩展这个例子。我可以使用它,但是我不知道是否有更简单的方法:

interface StateCount {
    count: number;
}

function Example() {
  const [countBox, setCount] = useState<StateCount>({count: 0});

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(countBox.count + 1)}>
        Click me
      </button>
    </div>
  );
}

现在,访问变量要复杂得多。是否可以通过这种方式声明它:

const [count, setCount] = useState<StateCount>(0);

然后以这种方式再次访问它?

<button onClick={() => setCount(count + 1)}>

2 个答案:

答案 0 :(得分:1)

如果您想使用StateCount作为状态的接口,则应该这样做。否则,您可以使用

const [countBox, setCountBox] = useState<number>(0);

//and set it as
setCount(countBox + 1)

答案 1 :(得分:1)

如果您不打算在StateCount中添加任何其他成员,则可以改用数字类型。

function Example() {
  const [count, setCount] = useState<number>(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Typescript也可能暗示类型是数字,因为您要指定初始值。

如果需要在状态中添加更多成员,则可以对所需的每个值进行多个useState调用;否则,您将必须访问您正在使用的特定成员。