import { useState } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
useState是React的一个hook that allows you to add state to functional components. It returns an array with two elements - the current state value, and a function to update itthat allows you to add state to functional components. It returns an array with two elements - the current state value, and a function to update it.
其他例子: 来自react官方文档tic-toc-toe tutorial
import { useState } from 'react';
function Square() {
const [value, setValue] = useState(null);
function handleClick() {
setValue('X');
}
return (
<button className="square" onClick={handleClick} >
{value}
</button>
);
}
export default function Board() {
const [squares, setSquares] = useState(Array(9).fill(null));
return (
// ...
);
}
<Square value={squares[3]} />