首页 > 解决方案 > 动态设置默认状态 + onMouseEnter

问题描述

我创建了一个记分牌,当用户将鼠标悬停在每个团队的卡片上时会更新,悬停在团队的卡片上还会更改一些 CSS 属性以使其脱颖而出。当前默认状态值为“0”,我需要默认值等于顶级球队的分数。下面是使用 onMouseEnter 更新 TopGroups 的 TeamCard 组件:

const TeamCard = ({
  data,
  setDisplayGoals,
  setDisplayMilestones,
  setDisplayPoints,
}) => {
  return (
    <TeamCardStyle>
      <Row className="d-flex justify-content-between">
        {!data && <Spinner />}
        {data &&
          data.getGroupScores &&
          data.getGroupScores.slice(0, 4).map((group, index) => {
            return (
              <Col
                key={guid()}
                className="teamCard mt-2 mb-2 mx-1"             
                onMouseEnter={() => [
                  setDisplayGoals(group.goalsDone),
                  setDisplayPoints(group.totalScore),
                  setDisplayMilestones(group.milestonesDone),
                ]}
              >
                <Row>
                  {/* <div className="arrow-down" /> */}
                  <p key={guid}>{seed[index]}</p>
                </Row>
                <Row>
                  <Col className="hideSmall">
                    <img className="mouseOn" src="../images/group.png" />
                    <img
                      className="mouseOff"
                      src="../images/groupSelected.png"
                    />
                  </Col>
                </Row>
                <p key={guid}>{group.name.slice(0, 14)}</p>
              </Col>
            );
          })}
      </Row>
    </TeamCardStyle>
  );
};

这是 TopGroups 组件的片段: 在此处输入图像描述

const TopGroups = () => {
  const currentQTR = `Q${moment().quarter()} ${moment().year()}`;
  const { loading, error, data } = useQuery(GET_GROUP_SCORES, {
    variables: { quarter: currentQTR },
  });
  if (data) {
    const sortedGroups = data.getGroupScores.sort((a, b) => {
      if (a.totalScore > b.totalScore) {
        return -1;
      }
      if (a.totalScore < b.totalScore) {
        return 1;
      } else {
        return 0;
      }
    });
    const test = data.GoalsDone;
  }
  if (error) {
    return <p>An error has occured</p>;
  }
  if (loading) {
    <Spinner />;
  }

  const [displayGoals, setDisplayGoals] = useState("0");
  const [displayPoints, setDisplayPoints] = useState("0");
  const [displayMilestones, setDisplayMilestones] = useState("0");

  return (
    <div className="row-12">
      <TeamCard
        data={data}
        setDisplayGoals={setDisplayGoals}
        setDisplayPoints={setDisplayPoints}
        setDisplayMilestones={setDisplayMilestones}
      />

我在第一次加载时包含了应用程序的图片,我希望这些零成为#1 Team 的分数,在这种情况下,它应该代表 Team Clown Car。

标签: reactjs

解决方案


也许您可以在获取数据时使用类似的东西

useEffect(()=>{
setDisplayGoals("first group's goals"),
setDisplayPoints("first group's points"),
setDisplayMilestones("first group's Milestones")
},[])

你明白了。空括号将导致 useEffect 仅在第一次渲染时运行。


推荐阅读