这个MCQ在ReactJs论文中被问到大学考试

问题描述 投票:0回答:1

以下哪种方法用于从成员函数内部访问组件的状态?

A] this.prototype.stateValue

B] 这个,getState()

C] this.values

D] this.state

请回答并解释一下,因为他们说 this.values 就是答案,一些网站也是如此。

但据我所知,this.values 在 React 中根本不存在。 I have done this code for understanding

import React, { Component } from "react";

class ClassBase extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
      message: "Hello",
    };
  }

  incrementCount = () => {
    this.setState((prevState) => ({
      count: prevState.count + 1,
    }));
    console.log("this.state " + this.state) // object
    console.log("this.values " + this.values) // undefined
    console.log("this.value " + this.value) // undefined

  };

  changeMessage = () => {
    this.setState({
      message: "Goodbye",
    });
  };

  render() {
    const { count, message } = this.state;



    return (
      <div>
        <h1>Count: {count}</h1>
        <button onClick={this.incrementCount}>Increment</button>
        <h1>Message: {message}</h1>
        <button onClick={this.changeMessage}>Change Message</button>
      </div>
    );
  }
}

export default ClassBase;
javascript reactjs class web web-development-server
1个回答
0
投票

我在同一所大学,教授声明了 this.value 来访问错误的状态,并且通过登录到控制台,它是未定义的。 this.state 是访问组件状态的唯一方法。

© www.soinside.com 2019 - 2024. All rights reserved.