[英]How to type state in React Hooks without adding typescript (like prop-type - in a simple way)
只是個小疑問。
如果我不想將 TS 添加到我的 React 項目中,但有時我需要一些類型檢查。
雖然對於道具我有一個簡單的道具類型解決方案,但對於 state 我什么也做不了。
那么有什么解決辦法嗎?
import PropTypes from 'prop-types';
//https://reactjs.org/docs/typechecking-with-proptypes.html - prop-types
export function GreetingHook (props) {
const [name2, setName2] = useState(10);//won't generate a warning.
{
return (
<h1>Hello, {props.name}</h1>
);
}
}
GreetingHook.propTypes = {
name: PropTypes.string,
name2: PropTypes.string
};
//Some parent...
//Will generate a warning
<GreetingHook name = {5}/>
注意 - 關於 class 組件也應該問同樣的問題。
您可以使用flow而不是 typescript,對於類型檢查,您可以通過以下方式進行:
const [name2, setName2] = useState(10);
(name2: number);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.