我是Reactjs的新手。我正在使用Google表单之类的调查创建的应用程序。我的组件有一个按钮,用于创建带有一些HTML元素的新Div来创建调查问题。为此,在按钮单击功能上,我正在创建一个JSX元素并将其推到数组中。然后,我在render函数中设置数组以显示其中的内容。
问题是,即使数组正在更新,动态HTML部分也无法在页面上看到。除按钮外,该页面为空。我怎样才能解决这个问题?
零件:
import '../../styles/css/surveycreation.css';
import React, { Component } from 'react';
let questionId = 0;
class SurveyCreation extends Component {
constructor(props) {
super(props);
this.questionsList = [];
this.state = {
}
}
addQuestion = (e) => {
e.preventDefault();
questionId = questionId + 1;
this.questionsList.push(
<div key={questionId}>
question block
</div>
)
}
render() {
return (
<div>
<button onClick={e => this.addQuestion(e)}>Add Question</button>
<div>
{this.questionsList}
</div>
</div>
);
}
};
export default SurveyCreation;
You need to map your
this.questionsList
variable.您可以将“问题字符串”保存在数组中,然后迭代数组以打印div。 这样的东西。
我认为您在填充元素数组后不会重新渲染组件。
Try adding the
questionsList
to the component's state and modify youraddQuestion
method so that it creates a new array, finally call setState with the new array.react组件知道重新渲染的唯一方法是设置状态。因此,您应该在状态中有一个数组来回答问题,然后根据该数组进行渲染。在数组中,您要保留数据,而不是JSX元素。渲染时将创建元素。