gpt4 book ai didi

javascript - 如何在几乎没有变化的情况下重用 React 组件

转载 作者:行者123 更新时间:2023-11-28 14:09:53 25 4
gpt4 key购买 nike

我想重新创建一些东西similar to this使用 react 。我还想为 2 个玩家使用 1 个玩家组件。既然两个玩家都有一个递增和递减按钮,我怎样才能让App.js区分两个玩家之间的差异呢?我知道我可以将它作为参数传递,但是我在哪里设置它?

这就是我为 App.js 所做的,显然,它适用于单个玩家:

constructor(props) {
super(props);
this.state = {
player1: 20,
player2: 20
};
}

increment = () => {
this.setState({
player1: this.state.player1 + 1,
player2: this.state.player2
};

最佳答案

您可以将参数传递给增量函数来指示它是哪个玩家

 increment = (p) => {
this.setState({
[p]: this.state[p] + 1,
};

并相应地将处理程序传递给 Player 实例:


return (
<Player increment={() => { this.increment('player1') }} />
<Player increment={() => { this.increment('player2') }} />
)

在你的 Player 组件中你会做类似的事情


const Player = (props) => {
return (
// I assume you would have some button somewhere
<button onClick={() => { props.increment() }}
)

}

关于javascript - 如何在几乎没有变化的情况下重用 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59973309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com