BFE.devAI解答 - React 代码题
7. useToggle()
useToggle()
is a custom React Hook that returns an array with two elements. The first element is a boolean value that represents whether the toggle is on or off, and the second element is a function that can be called to toggle the value of the boolean.
Here is an example implementation of useToggle()
:
import { useState } from 'react'function useToggle(initialValue: boolean = false): [boolean, () => void] { const [value, setValue] = useState(initialValue) const toggle = () => setValue(!value) return [value, toggle]}
This implementation uses useState()
to create a state variable to represent the boolean value. The toggle
function simply negates the current value of the state variable using the !
operator.
With this implementation, the App
component can use useToggle()
as follows:
function App() { const [on, toggle] = useToggle() return ( <> <span>{on ? 'ON' : 'OFF'}</span> <button onClick={toggle}>Toggle</button> </> )}
In this example, the on
variable is the boolean value returned by useToggle()
, and the toggle
function is the function returned by useToggle()
. The component renders a span
element that displays either "ON" or "OFF" based on the value of on
, and a button
element that calls toggle
when clicked.