由于无法正确将点击处理程序从父级传递到子级,我一直在尝试重构记分板组件。我在做什么错了?
这是我的组件结构
import React, { useState } from "react";
import "./App.css";
function ScoreBoard(props) {
return (
<section className="scoreboard">
<div className="topRow">
<div className="home">
<h2 className="home__name">{props.data.home.name}</h2>
<div className="home__score">{props.data.home.score}</div>
</div>
<div className="timer">00:03</div>
<div className="away">
<h2 className="away__name">{props.data.away.name}</h2>
<div className="away__score">{props.data.away.score}</div>
</div>
</div>
<BottomRow />
</section>
);
}
function TDButton(props) {
return (
<button className={props.side + "Buttons__touchdown"}>
{props.side.toUpperCase() + " Touchdown"}
</button>
);
}
function FGButton(props) {
/* similar to TDButton */
}
function Buttons(props) {
let scoreCounter = props.scoreCounter;
return (
<section className="buttons">
<div className="homeButtons">
<TDButton side="home" onClick={scoreCounter("Lions", 7)} />
<TDButton side="away" onClick={scoreCounter("Tigers", 7)} />
</div>
<div className="awayButtons">
<FGButton side="home" onClick={scoreCounter("Lions", 3)} />
<FGButton side="away" onClick={scoreCounter("Tigers", 3)} />
</div>
</section>
);
}
function App() {
const data = {
home: { name: "Lions", score: 32 },
away: { name: "Tigers", score: 32 }
};
const [homeScore, sethomeScore] = useState(data.home.score);
const [awayScore, setawayScore] = useState(data.away.score);
const scoreCounter = (team, amount) => {
if (team === data.home.name) {
console.log("in");
sethomeScore(homeScore + amount);
} else {
console.log("out");
setawayScore(awayScore + amount);
}
};
return (
<div className="container">
<ScoreBoard data={data} />
<Buttons data={data} scoreCounter={() => scoreCounter} />
</div>
);
}
最初的组件都存在于App中,因此我试图将其分解为较小的组件。我似乎无法使点击处理程序正常工作。我究竟做错了什么?也许我的组件故障可以得到改善?谢谢!
答案 0 :(得分:0)
因此,您必须在JSX中调用该函数
<Buttons data={data} scoreCounter={() => scoreCounter()} />
如果需要,您可以将值传递给函数。
答案 1 :(得分:0)
您在TButton中添加了道具,但没有在内部使用它。使用类似这样的内容:
function TDButton(props) {
return (
<button className={props.side + "Buttons__touchdown"} onClick={props.onClick}>
{props.side.toUpperCase() + " Touchdown"}
</button>
);
}
所以就像:
<TDButton side="home" onClick={scoreCounter("Lions", 7)} />
<button className={props.side + "Buttons__touchdown"} onClick={scoreCounter("Lions", 7)}>
{props.side.toUpperCase() + " Touchdown"}
</button>
因为您要将道具传递给父母的活动。
但这仅在scoreCounter(“ Lions”,7)返回一个函数时才起作用,如果它是常规函数,则需要执行操作:
<TDButton side="home" onClick={() => scoreCounter("Lions", 7)} />
所以props是一个函数,而不是函数返回的值。
这也许不是您想要的:
<Buttons data={data} scoreCounter={() => scoreCounter} />
scoreCounter将是返回函数值的函数(回答先前的观点,但您确实需要普通函数,因为上面的函数没有参数,而您使用的“ Lion”将被忽略):
<Buttons data={data} scoreCounter={scoreCounter} />