如何在React Js中单独更新一个子组件

问题描述 投票:0回答:1

我正在制作游戏Bingo的反应版本。我添加了25个作为子组件的按钮。最初我在每个按钮中都有空值。然后,在每次单击时,我试图将单击按钮的值从1更新为25。但是,当我单击一个按钮以更新按钮标签时,所有按钮的值都将更新。任何人都可以提出其背后的原因吗?

App.js

import React from "react";
import "./styles.css";
import GameContainerOne from "./GameContainerOne";

export default function App() {
  return (
    <div className="App">
      <GameContainerOne />
    </div>
  );
}

GameContainerOne.js

import React from "react";
import ButtonBox from "./ButtonBox";

class GameContainerOne extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      btnLabel: 0
    };
  }
  handleClicked = () => {
    if (this.state.btnLabel < 25) {
      this.setState({ btnLabel: ++this.state.btnLabel });
      console.log("after", this.state.btnLabel);
    }
  };
  render() {
    let menuItems = [];
    let key = 0;
    for (let i = 0; i < 5; i++) {
      for (let j = 0; j < 5; j++) {
        let index = "" + i + j;
        // console.log(index)
        key++;
        menuItems.push(
          <ButtonBox
            key={key}
            index={index}
            value={this.state.btnLabel}
            handleClicked={this.handleClicked.bind(this)}
          />
        );
      }
    }
    return <div className="wrapper">{menuItems}</div>;
    // this.handleButtonBox()
  }
}
export default GameContainerOne;

ButtonBox.js

import React from "react";
import Button from "@material-ui/core/Button";

class ButtonBox extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      initialBtnColor: "Default",
      selectedBtnColor: "Primary"
    };
  }

  handleClick = () => {
    // console.log("before",this.state.btnLabel)

    this.setState({ initialBtnColor: "Primary" });
    return this.props.handleClicked;
  };

  render() {
    console.log("Key=", this.props);
    //   const { index } = this.props.index;
    console.log("Key=", this.props.index);
    return (
      <div>
        <Button
          variant="contained"
          color={this.state.initialBtnColor}
          onClick={this.props.handleClicked}
        >
          {this.props.value}
        </Button>
      </div>
    );
  }
}
export default ButtonBox;

请找到代码和框链接:https://codesandbox.io/s/bingo-game-6v01r

javascript reactjs react-component
1个回答
0
投票

您更改单击状态,这是所有按钮的标签来源。

您可以为所有按钮设置一个单独的状态以避免发生这种情况,并根据所单击按钮的索引对其进行更改。

© www.soinside.com 2019 - 2024. All rights reserved.