我有一个呈现下表的 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/