react 多个子组件复用,子组件事件处理拿到当前操作的组件而不是最后一个子组件
时间: 2023-08-18 08:25:04 浏览: 58
如果你想在 React 中实现多个子组件复用,并且在子组件事件处理中能够拿到当前操作的组件,可以使用 React 的 Context API。
首先,在父组件中定义一个 Context,通过 Context.Provider 来将当前组件作为 Context 的 value 传递给所有子组件。然后,在子组件中通过 Context.Consumer 来获取当前组件的值。
下面是一个示例代码:
```jsx
// 父组件
import React, { createContext, useState } from 'react';
// 创建一个 Context
const ComponentContext = createContext(null);
function ParentComponent() {
const [components, setComponents] = useState([]);
function handleAddComponent() {
setComponents(components => [...components, <ChildComponent key={components.length} />]);
}
const contextValue = {
components,
setComponents,
};
return (
<ComponentContext.Provider value={contextValue}>
<div>
{/* 渲染所有子组件 */}
{components}
</div>
<button onClick={handleAddComponent}>添加子组件</button>
</ComponentContext.Provider>
);
}
// 子组件
function ChildComponent() {
const { components, setComponents } = useContext(ComponentContext);
function handleRemove() {
// 通过 Context 获取当前组件的索引,并从父组件中移除
const index = components.indexOf(this);
setComponents(components => [
...components.slice(0, index),
...components.slice(index + 1),
]);
}
return (
<div>
<button onClick={handleRemove}>移除</button>
</div>
);
}
```
在上面的示例代码中,我们通过 Context 将父组件中的 components 数组和 setComponents 函数传递给所有子组件。在子组件中,我们通过 useContext 来获取当前组件所在的 Context,并从中获取 components 和 setComponents。在子组件中,我们可以通过 components 数组和当前组件的索引来获取当前组件的值,从而实现在子组件事件处理中拿到当前操作的组件。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)