1 回答
TA贡献1797条经验 获得超4个赞
我的目标是向数组中的每个组件添加一个信息/描述对象,以便在切换组件时,其他组件仍然消失,但现在根据切换的组件显示描述。
你不是真的想消失吧?听起来更像是您想要有条件地渲染组件。
更新
我误解了你的意图!现在他们消失了。
// hooks
const {useState} = React;
function Comp1(){
return <div><p>Component 1</p></div>
}
function Comp2(){
return <div><p>Component 2</p></div>
}
function Comp3(){
return <div><p>Component 3</p></div>
}
function Comp4(){
return <div><p>Component 4</p></div>
}
const array = [
{ id: 1, component: <Comp1/>, isVisible: true,
info: { id: 5, component: <div>info1</div>, isVisibleInfo: false } },
{ id: 2, component: <Comp2/>, isVisible: true,
info: { id: 6, component: <div>info2</div>, isVisibleInfo: false } },
{ id: 3, component: <Comp3/>, isVisible: true,
info: { id: 7, component: <div>info3</div>, isVisibleInfo: false } },
{ id: 4, component: <Comp4/>, isVisible: true,
info: { id: 8, component: <div>info4</div>, isVisibleInfo: false } }
];
const Test = () => {
const [items, setItems] = useState(array);
const handleClick = (number) => {
const triggeredItems = items.map((item) => {
if (item.id !== number) {
item.isVisible = !item.isVisible;
}
item.info.isVisibleInfo =! item.info.isVisibleInfo
return item;
});
setItems(triggeredItems);
};
return (
<div className="mt-1 pt-1 pb-3 px-3">
<div className="row text-center d-flex my-1">
{items.map(({ id, component, isVisible, info }) => (
isVisible ?
<div
key={id}
className="col-lg-3 col-md-6 mb-4 justify-content-center"
onClick={() => handleClick(id)}
hidden={!isVisible}
>
{ component }
{info.isVisibleInfo ?
<div
key={info.id}
className="col-lg-9 col-md-6 mb-4 justify-content-center"
>
{ info.component }
</div>
: null}
</div>
: null
))}
</div>
</div>
);
};
function App(){
return (
<div>
<Test />
</div>
);
};
// Render
ReactDOM.render(
<App />,
document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
添加回答
举报