[英]How to show/hide an item of array.map() based on onclick inside component
我想根据P_Gamestate
属性显示/隐藏 JSX 的一部分。 如果这正在进行中,我们将只显示我们单击的组件。 否则其他一切都应该隐藏起来。 这很困难,因为.map()
引用了播放列表中的所有元素。 我怎样才能做到这一点? 目前它将隐藏我单击的组件,但其他所有内容都将保持显示。
挑战.js:
export default function Challenges()
{
const [P_gameState, P_setGameState] = useState(GAME_STATE.BEFORE);
useEffect(() => {
async function getPlaylists() {
let querySnapshot = await firestoreRef
.collection('challenge_test')
.get();
querySnapshot.forEach(function(data) {
playlist.push([useful data]);
});
}
getPlaylists();
},[]);
return(
<div>
<header>
{console.log("rendering component...")}
{playlist.map((row)=> (
<CardComponent key={row[0]}
name={row[0]}
image={row[1]}
creator={row[2]}
challengeID={row[3]}
P_gameState={P_gameState}
/>
)
)
}
</div>
);
}
卡片组件.js
function CardComponent(props) {
const [gameState, setGameState] = useState(GAME_STATE.BEFORE);
const onClick = () => {
console.log(props.history);
props.history.push("/playchallenge");
};
return (
<div>
{ gameState === GAME_STATE.BEFORE &&
<div className='card-component'>
<Button onClick={() => setGameState(GAME_STATE.IN_PROGRESS)}>
<img
className="playlist-image"
src={props.image}
alt={props.name} />
</Button>
<h3 className='playlist-title'>{props.name}</h3>
<h4 className='playlist-creator-text'>Created by {props.creator}</h4>
</div>
}
{ gameState === GAME_STATE.IN_PROGRESS && <FetchData />}
</div>
)
}
如果你想在 JSX 中进行条件渲染,你有多种方法:
map
function 回调内部分支array.map(item => {
if (!condition) {
return null;
}
return <Component {...props} />;
});
array.filter
之前调用map
(这将每次创建过滤后数组的新副本)array.map(item => condition && <Component {...props} />);
array.map(item => condition? <Component {...props} />: <SomethingElse />);
============
如果您希望内部组件中发生某些事件来更新条件,请使用事件道具
<CardComponent onClick={() => { /* do something with your game state */ }} />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.