react钩子函数有哪些,怎么用
时间: 2024-05-01 19:16:33 浏览: 97
常用的React钩子函数有:
1. useState:用于在函数组件中定义状态和更新状态的函数。
2. useEffect:用于在函数组件中执行副作用操作,例如获取数据、订阅事件、更新DOM等。
3. useContext:用于在函数组件中访问React上下文,避免了props的传递。
4. useCallback:用于在函数组件中定义回调函数,避免了不必要的渲染。
5. useMemo:用于在函数组件中进行性能优化,避免了不必要的计算。
6. useRef:用于在函数组件中保存变量,避免了变量被重复声明。
使用方法:
1. useState:
```
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. useEffect:
```
import React, { useEffect, useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
```
3. useContext:
```
import React, { useContext } from 'react';
const ThemeContext = React.createContext('light');
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
const theme = useContext(ThemeContext);
return (
<div>
<button style={{ background: theme }}>Toggle Theme</button>
</div>
);
}
```
4. useCallback:
```
import React, { useCallback, useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
setCount(count + 1);
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={handleClick}>
Click me
</button>
</div>
);
}
```
5. useMemo:
```
import React, { useMemo, useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
const doubleCount = useMemo(() => {
return count * 2;
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<p>Double count: {doubleCount}</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
```
6. useRef:
```
import React, { useRef } from 'react';
function Example() {
const inputRef = useRef(null);
const handleClick = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={handleClick}>
Focus input
</button>
</div>
);
}
```
阅读全文