如何访问方法内部的属性?

时间:2019-03-23 10:41:23

标签: javascript reactjs

我试图让用户单击“显示问题”按钮,以便通过调用handleQuestion()来改变状态,但是我收到以下错误声明“问题未定义”。

我想知道做错了什么,或者有更现实的方法做

class App extends React.Component {

  constructor(props){
    super(props);
    this.state = {
      question : [],
    };
  }

  questions = [
        {
          question: "Who is the strongest?",
          answers: {
            a: "Superman",
            b: "The Terminator",
            c: "Waluigi, obviously"
          },         
   ];

   handleQuestion(){    
     this.setState({
       question: questions
     });    
   }

   render(){    
     return (    
      <div className = "container">
       <button type="button" onClick={()=>this.handleQuestion()}>
         Show Question
       </button>    
     </div>
    );
  }
}

3 个答案:

答案 0 :(得分:2)

可以使用上下文this访问类中的属性。因此,这可以正常工作:

this.setState({
  question: this.questions
})

您用来声明questions的语法是非常新的(请参见stage3 -> class field),您的环境可能会或可能不支持这种语法。

如果没有,您可以选择使用函数包装器,例如:

questions() {
   return [...]
}

然后您可以这样做:

question: this.questions()

或在类外部或questions方法本身内部设置handleQuestion。这样一来,您就无需使用this来访问questions

答案 1 :(得分:1)

我对您的代码进行了一些更改,对我来说它们工作正常,请尝试一下,请阅读代码中的注释

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      question: []
    };
  }
  questions = { // 1. use {} bracket in place of [] you using object
    question: "Who is the strongest?",
    answers: {
      a: "Superman",
      b: "The Terminator",
      c: "Waluigi, obviously"
    }
  };
  handleQuestion() {
    this.setState({
      question: this.questions //2. hear use this.questions because you are accessing class variable   
    });
  }

  render() {
    return (
        <div className="container">
          <button type="button" onClick={() => this.handleQuestion()}>
            Show Question
          </button>
          {this.state.question["question"]}
        </div>

    );
  }
}

此更改之后,我认为您的代码可以正常工作:)

答案 2 :(得分:0)

import React, { Component } from 'react'; 
import logo from './logo.svg';
import './App.css'; 
var questions =[]
class App extends Component {
constructor(props){
super(props);
questions=  [
{
  question: "Who is the strongest?",
  answers: {
    a: "Superman",
    b: "The Terminator",
    c: "Waluigi, obviously"
  }
}         
];
this.state = {
    question : [],
};
}

handleQuestion(){ 
  this.setState({
  question: questions
});    
}

render(){    
  return (    
      <div className = "container">
      <button type="button" onClick={()=>this.handleQuestion()}>
        Show Question
      </button>   
      <ul>
        {this.state.question.map((data,i)=>(

            <li key={i}>{data.question}       
              <div>a : {data.answers.a}</div>
              <div>b : {data.answers.b}</div>
              <div>c : {data.answers.c}</div>
            </li>

          ))
         }
      </ul> 
   </div> 
 ); 
 }
 }

 export default App;

我进行了一些更改,您可以检查代码,运行它