我在下面有这个组件,changeColor()
函数导致错误消息:
TypeError: Cannot set property 'color' of undefined
这是组件中唯一的错误。所有其他事情都在顺利进行。 JSON 数据获取良好,组件渲染也很好。当然是在我实现阻止应用程序的函数 changeColor()
之前。
import React, { Component } from 'react'
var data = require('./db.json');
class Cronology extends Component {
constructor(props) {
super(props)
this.state = {
cronology: [],
year: "",
description: ""
}
this.changeColor = this.changeColor.bind(this)
}
componentDidUpdate() {
this.setState({
cronology: data.cronology
})
this.changeColor();
}
changeColor() {
document.querySelectorAll('p').style.color = 'red'
}
render() {
return (
<table>
{
this.state.cronology && this.state.cronology.map(
(i) => {
return (
<tr>
<th className="column1">• {i.year}</th>
<th className="column2"><p>{i.description}</p></th>
</tr>
)
}
)
}
</table>
)
}
}
export default Cronology;
最佳答案
您的 changeColor()
方法使用 document.querySelectorAll('p')
返回一个集合。您必须针对特定元素。
document.querySelectorAll('p')[0].style.color = "red"
例如
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
关于javascript - ReactJS - 未定义的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56454497/