在React中,可以通过使用状态管理来实现一次在一个组件上设置活动状态,并删除其他组件的活动状态。以下是一种实现方式:
import React, { useState } from 'react';
function ParentComponent() {
const [activeComponent, setActiveComponent] = useState(null);
// ...
}
function ChildComponent({ id, setActiveComponent }) {
const handleClick = () => {
setActiveComponent(id);
};
// ...
return (
<div onClick={handleClick}>
{/* 子组件内容 */}
</div>
);
}
function ParentComponent() {
const [activeComponent, setActiveComponent] = useState(null);
const handleSetActiveComponent = (id) => {
setActiveComponent(id);
};
const components = [
{ id: 1, name: 'Component 1' },
{ id: 2, name: 'Component 2' },
{ id: 3, name: 'Component 3' },
// ...
];
return (
<div>
{components.map((component) => (
<ChildComponent
key={component.id}
id={component.id}
setActiveComponent={handleSetActiveComponent}
/>
))}
</div>
);
}
function ParentComponent() {
const [activeComponent, setActiveComponent] = useState(null);
const handleSetActiveComponent = (id) => {
setActiveComponent(id);
};
const components = [
{ id: 1, name: 'Component 1' },
{ id: 2, name: 'Component 2' },
{ id: 3, name: 'Component 3' },
// ...
];
return (
<div>
{components.map((component) => (
<ChildComponent
key={component.id}
id={component.id}
setActiveComponent={handleSetActiveComponent}
/>
))}
{components.map((component) => (
<div
key={component.id}
style={{ display: activeComponent === component.id ? 'block' : 'none' }}
>
{/* 显示活动组件的内容 */}
</div>
))}
</div>
);
}
通过以上步骤,我们可以实现在React中一次设置一个组件的活动状态,并删除其他组件的活动状态。
领取专属 10元无门槛券
手把手带您无忧上云