javascript - ReactJS - 未定义的元素
问题描述
我在下面有这个组件,并且该changeColor()
功能导致错误,导致错误消息:
TypeError:无法设置未定义的属性“颜色”
这是组件中的唯一错误。所有其他事情都顺利进行。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')
which 返回一个集合。您必须针对特定元素。
document.querySelectorAll('p')[0].style.color = "red"
例如
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
推荐阅读
- angular - 使用角度的对话流聊天机器人中的用户身份验证
- iteration - 如何解决 Ocaml 循环中的语法错误?
- android - SMS Retriver Api 不会在某些设备上自动获取短信代码。[不是签名问题]
- sql - 基于相同的键将多行合并为一行
- java - 在android中查看没有按钮单击的实例
- google-cloud-platform - google cloud firestore datastore模式下实体组对事务的影响
- javascript - html表格水平滚动启用特定列
- c# - .Net Core System.Text.Json 以最小日期时间和 UTC 偏移量失败
- twilio - Twilio 出站 IVR
- sql - 如何根据条件合并两个 SQL Server 表?