react React.useState设置参数类型为数字怎么写
时间: 2024-05-10 13:13:57 浏览: 199
react.js 翻页插件实例代码
在 React 中,可以使用 TypeScript 或 PropTypes 为组件中的 props 和 state 设置类型。对于使用 useState Hook 设置数字类型的 state,可以这样写:
1. TypeScript:
```typescript
import React, { useState } from "react";
interface Props {}
const ExampleComponent: React.FC<Props> = () => {
const [count, setCount] = useState<number>(0);
const handleIncrement = () => {
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={handleIncrement}>Increment</button>
</div>
);
};
export default ExampleComponent;
```
2. PropTypes:
```javascript
import React, { useState } from "react";
import PropTypes from "prop-types";
const ExampleComponent = (props) => {
const [count, setCount] = useState(0);
const handleIncrement = () => {
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={handleIncrement}>Increment</button>
</div>
);
};
ExampleComponent.propTypes = {
// other PropTypes
count: PropTypes.number,
};
export default ExampleComponent;
```
阅读全文