Appearance
自定义 hooks
示例
我们这里用一个按钮点击后改变文本颜色的案例来展示自定义 hooks
hooks 文件名
在 React 中自定义 hooks 文件一般使用 use 开头
jsx 中
jsx
import { useState } from 'react'
import { Button } from './Button'
import useColorSwitch from './useColorSwitch'
function App() {
const [color1, handleBtn1Click] = useColorSwitch()
const [color2, handleBtn2Click] = useColorSwitch('#ffff00', '#00ffff')
return (
<div className="App">
<Button
label="按钮"
onClick={handleBtn1Click}
>
</Button>
<p style={{ color: color1 }}>这里演示useState的使用</p>
<Button
label="button"
onClick={handleBtn2Click}
>
<span>这里时children内容</span>
</Button>
<p style={{ color: color2 }}>这里演示useState的使用</p>
</div>
)
}
export default App
自定义 hooks 文件
js
import { useState } from 'react'
function useColorSwitch(color1 = '#ff00ff', color2 = '#ff0000') {
const [color, setColor] = useState(color1)
const handleBtnClick = () => {
setColor(color2)
}
return [color, handleBtnClick]
}
export default useColorSwitch