简体   繁体   中英

How can i pass different props to more than one children component from the parent one in React?

Im working on a color palette generator in React, and the problem i have is that when i try to pass different colors to every one of the child divs that will form the color palette every one gets the same color.

Here is the code

    class ColorPaletteContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      color: null,
    };
    this.setRandomColor = this.setRandomColor.bind(this);
  }

  setRandomColor() {
    let randomColor = "rgb(";
    for (let i = 0; i < 3; i++) {
      randomColor += Math.floor(Math.random() * 255);
      if (i < 2) {
        randomColor += ",";
      }
    }
    randomColor += ")";
    this.setState({
      color: randomColor,
    });
  }

  render() {
    return (
      <>
        <ColorDiv color={this.state.color}></ColorDiv>
        <ColorDiv color={this.state.color}></ColorDiv>
        <ColorDiv color={this.state.color}></ColorDiv>
        <button onClick={this.setRandomColor}>Press me!</button>
      </>
    );
  }
}

class ColorDiv extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>
        <h1 style={{ background: this.props.color }}>This is a color div!</h1>
      </div>
    );
  }
}

Basically the parent component passes the same color to all the 3 child components, because im passing the same state. Any idea of how i can pass different colors?

Make your state an array of colors like

this.state = {
  colors: [],
}

Then generate and push n randoms colors into it, iterate over the array and render the children

It will look something like this:

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      colors: []
    };
    this.setRandomColors = this.setRandomColors.bind(this);
  }

  generateRandomColor() {
    let randomColor = "rgb(";
    for (let i = 0; i < 3; i++) {
      randomColor += Math.floor(Math.random() * 255);
      if (i < 2) {
        randomColor += ",";
      }
    }
    randomColor += ")";
    return randomColor;
  }
  setRandomColors() {
    const colors = [];
    for (let i = 0; i < 3; i++) {
      colors.push(this.generateRandomColor());
    }
    this.setState(() => { return {colors: colors}; });
  }

  render() {
    return (
      <>
        {this.state.colors.map((color) => {
          return <ColorDiv color={color}></ColorDiv>;
        })}
        <button onClick={this.setRandomColors}>Press me!</button>
      </>
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM