1。管理简单状态:
import React, { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
2。管理布尔国家:
import React, { useState } from 'react';
function Example() {
const [isOn, setIsOn] = useState(false);
return (
<div>
<p>The light is {isOn ? 'on' : 'off'}</p>
<button onClick={() => setIsOn(!isOn)}>
{isOn ? 'Turn off' : 'Turn on'}
</button>
</div>
);
}
3。管理复杂状态:
import React, { useState } from 'react';
function Example() {
const [person, setPerson] = useState({ name: '', age: 0 });
const handleInputChange = event => {
const { name, value } = event.target;
setPerson({ ...person, [name]: value });
};
return (
<div>
<p>Name: {person.name}</p>
<p>Age: {person.age}</p>
<input
type="text"
name="name"
value={person.name}
onChange={handleInputChange}
/>
<input
type="number"
name="age"
value={person.age}
onChange={handleInputChange}
/>
</div>
);
}
4。管理数组状态:
import React, { useState } from 'react';
function Example() {
const [todos, setTodos] = useState([]);
const handleAddTodo = () => {
setTodos([...todos, { id: Date.now(), text: 'New todo' }]);
};
return (
<div>
<ul>
{todos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
<button onClick={handleAddTodo}>Add todo</button>
</div>
);
}
5。根据以前的状态更新状态:
import React, { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
const handleIncrement = () => {
setCount(prevCount => prevCount + 1);
};
return (
<div>
<p>You clicked {count} times</p>
<button onClick={handleIncrement}>Click me</button>
</div>
);
}
这些只是Usestate挂钩许多用例的几个示例。钩子非常通用,可用于管理React组件中的任何状态。