Javascript ReactJS-未定义元素

Javascript ReactJS-未定义元素,javascript,css,reactjs,Javascript,Css,Reactjs,我在下面有一个组件,由于changeColor()函数导致错误,导致错误消息: TypeError:无法设置未定义的属性“color” 这是组件中唯一的错误。所有其他事情都在顺利进行。JSON数据提取良好,组件渲染也很好。当然是在我实现阻止应用程序的函数changeColor()之前 import React, { Component } from 'react' var data = require('./db.json'); class Cronology extends Compone

我在下面有一个组件,由于
changeColor()
函数导致错误,导致错误消息:

TypeError:无法设置未定义的属性“color”

这是组件中唯一的错误。所有其他事情都在顺利进行。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;
import React,{Component}来自“React”
var data=require('./db.json');
类Cronology扩展组件{
建造师(道具){
超级(道具)
此.state={
权杖学:[],
年份:“,
说明:“”
}
this.changeColor=this.changeColor.bind(this)
}
componentDidUpdate(){
这是我的国家({
权变学:数据。权变学
})
这个;
}
changeColor(){
document.querySelectorAll('p').style.color='red'
}
render(){
返回(
{
this.state.cronology&&this.state.cronology.map(
(i) =>{
返回(
•{i.year}
{i.description}

) } ) } ) } } 导出默认密码;
您的
changeColor()
方法正在使用返回集合的
document.queryselectoral('p')
。您必须以特定元素为目标


document.querySelectorAll('p')[0]。例如style.color=“red”


作为对他人答案的补充,您可以使用
forEach
,即:

document.queryselectoral('p').forEach(el=>el.style.color='red')

文档。queryselectoral('p')
将返回类似数组的结构,您可以使用
文档。queryselectoral('p')[0]。style.color='red'
更改第一个p元素的颜色。