javascript - ReactJS - 如何在使用数组时设置 <td> 标签的样式?

标签 javascript css reactjs

我有一个呈现下表的 Table React 组件。这个 Table 类接收一个名为 array 的 Prop ,假设其中有 10 个元素。所以我基本上是通过 array 并将每个元素添加到一个新行。我想要做的是,当用户点击应用中的特定按钮时,id 为 foo 的列应该变为黄色。

class Table extends React.Component {
  render() {
    return (
      <table>
          <thead>
            <tr><th>Heading 1</th></tr>
          </thead>
          <tbody>
            {this.props.array.map(element =>
              <tr key={element}>
                <td id="foo">{element}</td>
              </tr>
            )}
          </tbody>
      </table>
    );
  }
}

现在,我正在尝试做这样的事情:

class Bar extends React.Component {
  row;

  componentDidMount() {
    this.row = document.getElementById("foo");
  }

  render() {
    return {
      <button onClick={(event) => {
        this.update();
      }}>I will turn the #foo column yellow!
      </button>
    }
  }

  update() {
    this.row.classList.add('yellow-color');
  }
}

CSS:

.yellow-color {
  background-color: yellow;
}

但是,它不会将该列变为黄色。有谁知道为什么会这样?我该如何解决这个问题?谢谢!

最佳答案

你不应该在 React 中使用 document.getElementById()。您可以使用 Refs 实现类似的效果, 尽管不推荐。

您可以通过使用状态和传递 Prop 来实现相同的目的。

class Table extends React.Component {
  state = {
    color: "black"
  };
  update = () => {
    this.setState({
      color: "yellow"
    })
  }
  render() {
    return (
      <div>
      <button onClick={(event) => {
        this.update();
      }}>I will turn the #foo column yellow!
      </button>
      <table>
          <thead>
            <tr><th>Heading 1</th></tr>
          </thead>
          <tbody>
            {this.props.array.map(element =>
              <tr key={element}>
                <td style={{ backgroundColor: this.state.color }}>
                  {element}
                </td>
              </tr>
            )}
          </tbody>
      </table>
      </div>
    );
  }
}

关于javascript - ReactJS - 如何在使用数组时设置 <td> 标签的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51202558/

相关文章:

javascript - 计算贝塞尔曲线下的面积

javascript - XHR加载失败: POST

javascript - AngularJS 模板中的三元运算符

javascript - Typescript import index.ts 不是一个模块

javascript - setFindTimeout 和 pollUntil with Intern 用于在初始页面加载时不可见的元素

css - 我无法编辑 drupal 模块,CSS 位置很难找到

html - 设置div的背景色

html - 元素在不同浏览器中显示不同

reactjs - 在 onDragStop 事件中获取 Material UI Slider 值

javascript - 无法读取未定义的属性 'string' | React.PropTypes | React.PropTypes | LayoutPropTypes.js