【问题标题】:Setting attributes on click in React JS在 React JS 中点击设置属性
【发布时间】:2021-01-10 07:47:13
【问题描述】:

我正在努力做到这一点,所以当我点击下面动态创建的元素时,它们会改变颜色。

  handleBuild() {
    const from = parseInt(document.getElementById("from").value);
    const to = parseInt(document.getElementById("to").value);
    let newSquares = [];
    for (let i = from; i <= to; i = i + 0.5) {
      if (i.toString().includes(".")) {
        newSquares.push(i.toString().split(".", 1) + ":30");
      } else {
        newSquares.push(i.toString());
      }
    }
    this.setState({ squares: newSquares });
  }

  render() {
    const items = this.state.squares.map((item) => (
      <div
        name={item}
        onClick={() => this.handleColor}
        className="squares"
        key={item}
      >
        <h4>{item}</h4>
      </div>
    ));

我想知道我的handleColor 函数应该是什么样子?我有一个可以用来改变颜色的状态,但首先我想知道如何在反应中改变动态创建的 DIV 的颜色?我应该将哪些信息传递给函数以选择该 DIV 并在单击时更改其样式属性?

提前致谢

【问题讨论】:

    标签: javascript reactjs colors onclick styles


    【解决方案1】:

    您需要传递数组元素的索引来识别数组中的元素。在 handleColor 函数中,从数组中提取该项目并根据索引进行更新并更新状态。

    handleColor = (index) => {
      const squares = this.state.squares
      const item = this.state.squares[index]
      item.color = "#fff" // any random color
      squares[index] = item
      this.setState({
        squares
       })
    
    const items = this.state.squares.map((item,index) => (
      <div
        name={item}
        style={{ color: item.color}}
        onClick={(index) => this.handleColor(index)}
        className="squares"
        key={item}
      >
        <h4>{item}</h4>
      </div>
    ));
    

    【讨论】:

    • 我已经尝试了很多年,我要放弃了。你能告诉我我需要研究什么来了解动态渲染 DIV,然后再访问这些 DIV 吗?谢谢
    • 实践让你完美。不要放弃。随着时间的推移,你会掌握。如果卡在某个地方,如果没有得到结果,只需在 stackoverflow 上发布,社区会帮助您识别问题。您可以观看 maxmillian 或其他 youtuber 对 youtube 频道的反应。
    猜你喜欢
    • 2018-11-11
    • 2021-05-29
    • 1970-01-01
    • 2013-08-28
    • 2017-11-03
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    相关资源
    最近更新 更多