首页 > 解决方案 > 我如何重用几乎没有变化的 React 组件

问题描述

我想使用 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
  };

标签: javascriptreactjs

解决方案


您可以将参数传递给您的增量函数,指示它是哪个播放器

 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() }}
    )

}

推荐阅读