【发布时间】:2019-02-23 15:30:39
【问题描述】:
我的动态表单有一个小问题。在渲染方法下面的代码中,我有映射输入和下拉选择菜单的代码来填写 state.questions[{title: "", type: ""}]。您可以看到添加更多问题的 addQuestionsHandler 方法和处理问题值的 questionsInputHandler。
surveyInputHandler 方法处理返回函数中的静态问题。
我遇到的问题是,在我的动态问题代码中,输入值和选择下拉值最终在 state.questions [{title: "", type: ""}] 中结束。如果我输入“测试” - 标题和类型都将是“测试”。如果我输入“测试”并选择值 =“单选按钮” - 标题和类型都将是“单选按钮”。如果我不选择下拉选项值,那么两者都将是输入值。如果我确实选择了下拉选项值,则输入值将被下拉选择值覆盖。
我已经绞尽脑汁了一段时间,但我需要更多的关注。你能告诉我我做错了什么吗?非常感谢。
const questionTypes = [
"Select Question Type",
"Textbox",
"Radio Button",
"Checkbox"
];
class SurveyQuestions extends Component {
constructor(props) {
super(props);
this.state = {
title: "",
description: "",
pointsValue: 0,
questions: [
{
title: "",
type: ""
}
]
};
}
surveyInputHandler = e => {
console.log(e.target.value);
this.setState({
[e.target.name]: e.target.value,
[e.target.title]: e.target.value,
[e.target.description]: e.target.value,
[e.target.pointsValue]: e.target.value
});
};
questionsInputHandler = idx => e => {
console.log(e.target.value);
const newQuestions = this.state.questions.map((question, qidx) => {
if (idx !== qidx) return question;
return {
...question,
title: e.target.value,
type: e.target.value
};
});
this.setState({
questions: newQuestions
});
};
addQuestionHandler = () => {
this.setState(prevState => ({
questions: [...prevState.questions, { title: "", type: "" }]
}));
};
submitHandler = e => {
const { title, description, pointsValue, questions } = this.state;
console.log(
title,
description,
pointsValue,
questions.map(question => ({ ...question }))
);
this.setState({
title: "",
description: "",
pointsValue: "",
questions: [{ title: "", type: "" }]
});
e.preventDefault();
};
render() {
const { title, description, pointsValue, questions } = this.state;
const questionsDisplay = questions.map((question, idx) => (
<div key={idx} className="SurveyQuestions__QuestionContainer">
<h5>Question {idx + 1}</h5>
<label htmlFor="questionTitle">Question Title</label>
<input
type="text"
id="questionTitle"
placeholder={`Question Title #${idx + 1}`}
value={question.title}
onChange={this.questionsInputHandler(idx)}
/>
<label htmlFor="questionType">Type</label>
<select
className="SurveyQuestions__QuestionTypesDropdown"
value={question.type}
onChange={this.questionsInputHandler(idx)}
>
{questionTypes.map((type, tidx) => (
<option key={tidx} id={`${type}-${tidx}`} value={type}>
{type}
</option>
))}
</select>
</div>
));
【问题讨论】:
标签: javascript html reactjs dynamicform