以下为ChatGPT自动生成的解答,正确与否请自行判断。 也许你也可以从大家的发帖中找到想要的答案!
BFE.devAI解答 - React 代码题
12. useArray()
以下是实现 useArray()
的代码示例:
import { useState } from "react"function useArray(initialArray: any[]) { const [array, setArray] = useState(initialArray) function push(item: any) { setArray([...array, item]) } function removeByIndex(index: number) { const newArray = [...array] newArray.splice(index, 1) setArray(newArray) } return { value: array, push, removeByIndex, }}export default useArray
使用示例:
import useArray from "./useArray"function ExampleComponent() { const { value, push, removeByIndex } = useArray([1, 2, 3]) function handlePush() { push(4) } function handleRemove(index: number) { removeByIndex(index) } return ( <div> <ul> {value.map((val: any, index: number) => ( <li key={index}> {val} <button onClick={() => handleRemove(index)}>Remove</button> </li> ))} </ul> <button onClick={handlePush}>Push</button> </div> )}export default ExampleComponent
在上面的示例中,我们创建了一个 useArray()
hook,该 hook 接收一个初始数组并返回一个包含当前数组、push
和 removeByIndex
方法的对象。
push()
方法将项目添加到数组中,而 removeByIndex()
方法可根据指定的下标从数组中删除项目。
在 ExampleComponent
中,我们使用 useArray()
hook 来初始化数组,并定义了两个处理方法: handlePush
和 handleRemove
来处理插入和删除操作。在 render()
函数中,我们显示数组中的每个项目,并在每个项目旁边添加了一个删除按钮。同时,我们还为 push
方法创建了一个按钮。