首页 > 解决方案 > 您如何为组件的每个实例赋予其独立变化的道具?

问题描述

它当前的设置方式是,当单击一个cell组件时,每个单元格的背景颜色都会变为红色或黑色,而不仅仅是那个单元格。我怎样才能使每个cell组件的currentColor道具都是独一无二的并且独立更改?

相关位来自App.js

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      grid: [
        [{},{},{},{},{},{},{}],
        [{},{},{},{},{},{},{}],
        [{},{},{},{},{},{},{}],
        [{},{},{},{},{},{},{}],
        [{},{},{},{},{},{},{}],
     ],
      currentColor: "red",
    };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    console.log('The circle was clicked and will change to this color: ' + this.state.currentColor);
    if (this.state.currentColor === "red"){
      this.setState(state => ({
        currentColor: "black"
      }));
    }
    else{
      this.setState(state => ({
        currentColor: "red"
      }));
    }
  }


  render(){
    console.log("Grid length is: " + this.state.grid.length)
    return (
      <div className="App">
        <GridContainer grid={this.state.grid} currentColor={this.state.currentColor} handleClick={this.handleClick}/>
      </div>
    );
  }

}

export default App;

然后以这种方式传递这些道具:App -> GridContainer -> RowContainer -> Cell

子组件Cell.js

import React, { Component } from 'react';
import styled from 'styled-components'

const StyledCell = styled.div`
  background-color: ${props => props.currentColor};
  border-radius: 50%;
  margin: 1rem;
  width: 133px;
  height: 100px;
`;


class Cell extends Component {

  render() {
    return(
        <StyledCell onClick={this.props.handleClick} currentColor = {this.props.currentColor}>
        </StyledCell>
      )
  }

}

export default Cell;

标签: reactjs

解决方案


由于您在顶层更改了一次颜色,因此将相同的值传递给所有子组件。如果您想拥有特定于每个组件实例的颜色,您可以为 Cell 组件提供内部状态以控制其自己的颜色,或者将每个单元格的颜色独立存储在网格对象中,然后映射数组并传递每个颜色作为道具并调整处理程序以提升单元格的状态更改。我会举一个例子,但它几乎是 5。干杯。

更新:

我认为第二种方法可能更好,在这种情况下,您可以将应用程序的网格状态转换为:

this.state.grid = [
[{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" }],
[{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" }],
[{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" }],
[{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" }],
[{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" }]
]

并将您的点击处理程序替换为为您定位的特定单元格设置颜色的处理程序:

function colorCell(row, col, color) {
  let grid = Array.from(this.state.grid);
  grid[row][col].color = color;
  this.setState({ grid: grid })
}

像您正在做的那样,将该函数作为道具一直传递给您的单元格,以及它们各自的行/列索引,并在附加到单元格的单击处理程序中调用它。

无论如何,这就是要点。


推荐阅读