我有三个类,结构如下:
CreateTest.js -Question.js --Answer.js
在CreateTest中,我设置了一个问题组件数组,然后在Question.js中,我有一个Answer组件数组。问题类设置问题编号的状态,该状态从CreateTest调用。渲染时有效。
Question类从Answer.js调用一个方法来设置答案编号,但这似乎不会使状态保持不变。呈现时会给出this.state为null的错误。
我尝试过使用setState方法,但这是相同的。我认为这可能与同步有关,但是我很难理解这一点,并且不明白为什么树下的类与之不同。
Question.js类:
import React, { Component } from "react";
import Container from 'react-bootstrap/Container';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import Answer from './Answer';
class Question extends Component {
constructor(props) {
super(props);
this.handleAddAnswer = this.handleAddAnswer.bind(this);
this.state = {noofanswers: 0, answerarray: [] };
}
setQuestionNo(questionno) {
this.state = { questionno: questionno };
}
handleAddAnswer() {
var noofanswers = this.state.noofanswers + 1;
var answer = new Answer();
answer.setAnswerNo(noofanswers);
var answerarray = this.state.answerarray;
answerarray.push(answer);
this.setState({noofanswers: noofanswers, answerarray: answerarray});
}
render() {
return(
<Container>
<Row>
<p>Question {this.state.questionno}</p>
</Row>
<Row>
Question Text:
<input type="text" />
</Row>
<Row>
<button onClick={() => this.handleAddAnswer()}>Add Answer</button>
</Row>
<Row>
<p>{this.state.noofquestions}</p>
<div>{this.state.answerarray.map( () => (
<Answer />
) )}</div>
</Row>
</Container>
);
}
}
export default Question
Answer.js类:
import React, { Component } from "react";
import Container from 'react-bootstrap/Container';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
class Answer extends Component {
constructor(props) {
super(props);
}
setAnswerNo(answernum) {
this.state = {ansernumber: answernum };
//this.setState({ answerno: answerno });
}
render() {
alert(this.state.answernumber);
return(
<Container>
<Row>
<p>{this.state.answernumber} <input type="text" /></p>
</Row>
</Container>
);
}
}
export default Answer
如果需要,我可以发布CreateTest类。