3 回答

TA貢獻1784條經驗 獲得超2個贊
添加一個狀態來存儲點擊的(或者說,當前選擇的)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;

TA貢獻1797條經驗 獲得超6個贊
試試這個方法,
跟蹤狀態中選定的 div(使用 id)并Component根據狀態中選定的 div 更改顏色。
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
希望這是您正在尋找的用例。如果您遇到任何問題,請告訴我。

TA貢獻1871條經驗 獲得超8個贊
你可以添加狀態
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 選擇的項目
添加回答
舉報