【问题标题】:How can i pass different props to more than one children component from the parent one in React?如何在 React 中将不同的道具从父组件传递给多个子组件?
【发布时间】:2021-06-12 00:14:35
【问题描述】:

我正在使用 React 中的调色板生成器,我遇到的问题是,当我尝试将不同的颜色传递给将形成调色板的每个子 div 时,每个子 div 都会获得相同的颜色。

这里是代码

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

基本上,父组件将相同的颜色传递给所有 3 个子组件,因为我传递了相同的状态。知道如何传递不同的颜色吗?

【问题讨论】:

    标签: html reactjs web components


    【解决方案1】:

    让你的状态像一个颜色数组

    this.state = {
      colors: [],
    }
    

    然后生成 n 随机颜色并将其推送到其中,遍历数组并渲染子元素

    它看起来像这样:

    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>
          </>
        );
      }
    }
    

    【讨论】:

    • 这是一个很好的解决方案,但为了做到这一点,我需要知道要渲染多少子组件,我理想的解决方案是无论我放多少颜色 div,我总是为每个生成一个随机颜色。
    • 在您的问题中,您有 3 个硬编码的孩子。 “父组件将相同的颜色传递给所有 3 个子组件” 这是您的问题陈述。孩子的数量来自哪里?
    猜你喜欢
    • 2018-08-11
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 2021-07-04
    相关资源
    最近更新 更多