繁体   English   中英

如何在组件内部基于 onclick 显示/隐藏 array.map() 项

[英]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 中进行条件渲染,你有多种方法:

  1. map function 回调内部分支
array.map(item => {
  if (!condition) {
    return null;
  }
  return <Component {...props} />;
});
  1. 组件内部分支渲染 function(类似于方法一)
  2. array.filter之前调用map (这将每次创建过滤后数组的新副本)
  3. 带有逻辑 && 运算符的内联 If
array.map(item => condition && <Component {...props} />);
  1. 带有条件(三元)运算符的内联 If
array.map(item => condition? <Component {...props} />: <SomethingElse />);

============

如果您希望内部组件中发生某些事件来更新条件,请使用事件道具

<CardComponent onClick={() => { /* do something with your game state */ }} />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM