react父组件import Item from Itemimport useState from reactconst Todo = = const inputValue setInputValue = useState const value setValue = useState const handleAdd = e = if ekeyCode === 13 if !in
父组件中,将handleAddList方法作为props传递给子组件Item,并在子组件中调用该方法。
父组件修改后的代码如下:
import Item from './Item'
import { useState, useRef } from 'react'
const Todo = () => {
const [inputValue, setInputValue] = useState('')
const [value, setValue] = useState('')
const itemRef = useRef(null)
const handleAdd = e => {
if (e.keyCode === 13) {
if (!inputValue) return alert('请输入任务名称')
setValue(inputValue)
setInputValue('')
itemRef.current.handleAddList() // 调用子组件的handleAddList方法
}
}
return (
<div>
<input
className="add"
type="text"
placeholder="添加一项任务"
value={inputValue}
onChange={e => setInputValue(e.target.value.trim())}
onKeyUp={handleAdd}
/>
<Item value={value} ref={itemRef} /> {/* 将handleAddList方法作为props传递给子组件,并使用ref获取子组件的实例 */}
</div>
)
}
export default Todo
子组件中,使用useImperativeHandle和forwardRef获取父组件传递的handleAddList方法,修改后的代码如下:
import { useState, useImperativeHandle, forwardRef } from 'react'
const Item = ({ value }, ref) => {
const todoList = [
{
id: 1,
title: '学习webapi',
isDone: true,
},
]
const [renderList, setTodoList] = useState(todoList)
useImperativeHandle(ref, () => ({
handleAddList: () => {
if (!value) return
setTodoList([
{
id: todoList.length + 1,
title: value,
isDone: false,
},
...renderList,
])
},
})) // 使用useImperativeHandle获取父组件传递的handleAddList方法
return (
<ul>
{renderList.map(item => (
<li key={item.id}>
<label htmlFor="task">
<input type="radio" id="task" />
<span>{item.title}</span>
</label>
<b className="del">❌</b>
</li>
))}
{!todoList.length && <li>当前没有任务,请添加!</li>}
</ul>
)
}
export default forwardRef(Item)
通过使用useRef和forwardRef,父组件可以调用子组件的handleAddList方法
原文地址: https://www.cveoy.top/t/topic/ivlc 著作权归作者所有。请勿转载和采集!