您如何为组件的每个实例提供自己的独立更改的道具?

时间:2019-05-22 20:29:51

标签: reactjs

当前设置的方式是,单击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;

1 个答案:

答案 0 :(得分:1)

由于您一次在顶层更改了颜色,因此相同的值将向下传递到所有子组件。如果要使用特定于每个组件实例的颜色,则可以将内部状态赋予Cell组件以控制其自身的颜色,或者将每个单元格的颜色独立存储在网格对象中,然后映射到数组并传递每个将颜色设置为道具,并将处理程序调整为lift up,状态从单元格更改。我举一个例子,但差不多是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 })
}

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

那是要点。