首页 > 解决方案 > 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;

标签: javascriptcssreactjs

解决方案


您的changeColor()方法正在使用document.querySelectorAll('p')which 返回一个集合。您必须针对特定元素。

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

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll


推荐阅读