gpt4 book ai didi

typescript - react useState Prop : Type 'string' is not assignable to type 'number' . TS2322

转载 作者:行者123 更新时间:2023-12-04 14:53:47 25 4
gpt4 key购买 nike

我正在尝试将 Prop 传递给 React useState Hooks。我的 Prop 和数字都是必需的,但我收到 Typescript 错误:

Type 'string' is not assignable to type 'number'. TS2322


但我没有在任何地方传递字符串。所以,我不知道为什么我会得到这个 Typescript。我不想传 Prop any .
import React, { useState } from "react";
import ReactDOM from "react-dom";

interface Props {
strength: number;
speed: number;
}

const Courseinfo = ({ strength, speed }: Props) => (
<>
<div>
<h1>{strength}</h1>
<h1>{speed}</h1>
</div>
</>
);

const App = () => {
const [character, setCharacter] = useState<Props>({ // This Props throws me error
strength: 0,
speed: 0,
});

const { strength, speed } = character;
return (
<>
Strength:
<input
type="number"
value={strength}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setCharacter({ ...character, strength: e.target.value })
}
/>
Speed:
<input
type="number"
value={speed}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setCharacter({ ...character, speed: e.target.value })
}
/>
<Courseinfo strength={strength} speed={speed} />
</>
);
};

ReactDOM.render(<App />, document.getElementById("root"));

最佳答案

input type="number"的值是一个字符串
这是固定的 sandbox .
变化:

interface Props {
strength: string;
speed: string;
}
和事件的类型可以是
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
或者,您也可以转换 event.target.value到一个数字( +event.target.number )而不是改变 Prop 类型。

关于typescript - react useState Prop : Type 'string' is not assignable to type 'number' . TS2322,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68549934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com