如何在 class 组件的函数声明中使用 props 和 state?

How to use props and state inside a function declaration in a class component?

我有一个 class 组件,其中有一个名为 printData() 的函数 我想在这个函数中使用 class 的 states 和 props 变量。我该怎么做?

代码-

class ReadData extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: ""
        }
    }

    componentDidMount() {
        this.setState({ data: "Hello World" })
    }

    printData(props) {
        console.log(this.props.data)
    }

    render() {
        return (
            <div>
                <p>{this.state.data}</p>
                <button onClick={this.printData}>Print</button>
            </div>

        )
    }
}

实际代码不同。这是我正在尝试实现的示例。控制台显示

Uncaught (in promise) TypeError: Cannot read property 'props' of undefined

使用 this.state.data 而不是 this.props.data 也不起作用。

Note: The render return successfully prints the desired output on the window. Also, I want to make use of Class component and not functional component

您需要绑定函数或使用箭头函数 () => {} 才能使 this 工作。

参见文档:https://reactjs.org/docs/handling-events.html

class ReadData extends Component {
    constructor(props) {
        super(props);
        // This binding is necessary to make `this` work in the callback
        this.printData = this.printData.bind(this);
    }

    printData() {
        console.log(this.props.data)
    }

    render() {
        return (
            <div>
                <p>{this.state.data}</p>
                <button onClick={this.printData}>Print</button>
            </div>

        )
    }
}

class ReadData extends Component {
    // Use arrow function to make `this` work in the callback
    printData = () => {
        console.log(this.props.data)
    }

    render() {
        return (
            <div>
                <p>{this.state.data}</p>
                <button onClick={this.printData}>Print</button>
            </div>

        )
    }
}