[英]How to switch between sibiling in react
考慮我有一個這樣的 App 組件:
import React from "react";
import Component from "./component";
function App() {
const array = [
{ key : 1 } , { key : 2 } , { key : 3 } , { key : 4 }
]
return (
<div>
{array.map( (item) => {
<Component key={item.key} />
})}
</div>
);
}
export default App;
組件是:
import React , { useState } from "react";
function Component() {
const [ style , setStyle ]= useState({
height:"50px",width:"50px",backgroundColor:"blue"
});
return (
<div style={style} onclick={} >
Content
</div>
);
}
export default Component;
這將創建一個 App div,其中將有四個子 div 元素。
我想要的是; 每當我單擊內部 div 之一時,其余三個 div 必須將其顏色更改為紅色。 不是一次,而是每次我點擊四個中的任何一個時。
添加一個狀態來存儲點擊的(或者說,當前選擇的) div
import React, { useState } from "react";
import Component from "./component";
function App() {
const [selectedDiv, setSelectedDiv] = useState(-1);
const array = [
{ key : 1 } , { key : 2 } , { key : 3 } , { key : 4 }
]
return (
<div>
{array.map( (item) => {
<Component key={item.key} clickHandler={() => {setSelectedDiv(item.key)}} isColoured={(selectedDiv === item.key || selectedDiv < 0) ? false : true} />
})}
</div>
);
}
export default App;
現在在Component
,檢查isColoured
道具,如果它是true
,則應用顏色,否則不要。
import React from "react";
function Component(props) {
return (
<div onClick={props.clickHandler} style={props.isColoured ? {height:"50px",width:"50px",backgroundColor:"red"} : null}>
Content
</div>
);
}
export default Component;
你可以添加狀態
const [selectedId, setSelectedId] = useState(null);
然后制作一個函數來呈現在這種情況下的指南
const renderGuide = ({ item, index }) => {
console.log(item)
const backgroundColor = item.id === selectedId ? "#FFFFFF" : "#FFFFFF";
return (
<Guide
item={item}
index={index}
onPress={() => setSelectedId(item.id)}
style={{ backgroundColor }}
/>
);
};
使您可以訪問由 id 選擇的項目
試試這個方法,
跟蹤狀態中選定的 div(使用 id)並根據狀態中的選定 div 更改Component
顏色。
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [selectedId, setSelectedId] = useState(null);
const array = [{ key: 1 }, { key: 2 }, { key: 3 }, { key: 4 }];
return (
<div>
{array.map((item) => {
return (
<Component
key={item.key}
id={item.key}
selectedPanel={selectedId === item.key || selectedId === null}
onClick={() => setSelectedId(item.key)}
/>
);
})}
</div>
);
}
function Component({ id, onClick, selectedPanel }) {
return (
<div
className="panel"
style={{ backgroundColor: selectedPanel ? "blue" : "red" }}
onClick={onClick}
>
Content - {id}
</div>
);
}
工作代碼 - https://codesandbox.io/s/zealous-clarke-r3fmf?file=/src/App.js:0-770
希望這是您正在尋找的用例。 如果您遇到任何問題,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.