gpt4 book ai didi

javascript - React - 动态添加输入而不改变状态

转载 作者:行者123 更新时间:2023-11-30 14:02:12 26 4
gpt4 key购买 nike

我正在尝试在用户单击按钮添加问题时动态添加输入。

通常做受控表单很容易,因为您知道字段名称是什么。但在这种情况下,它们是动态的。

我有一个可行的解决方案,但它会改变状态。

有更好的方法吗?

谢谢

JSX

import React, { Component } from 'react';
import axios from 'axios';
import { saveAs } from 'file-saver';

class Form extends Component {
constructor(props) {
super(props);

this.onChange = this.onChange.bind(this);
this.handleForm = this.handleForm.bind(this);
this.addQuestion = this.addQuestion.bind(this);
this.removeQuestion = this.removeQuestion.bind(this);

this.state = {
questions: []
}
}
onChange(e, i) {
this.state.questions[i] = e.target.value;

this.setState({
questions: this.state.questions
})
}
handleForm(e) {
e.preventDefault();

const body = {
questions: this.state.questions
};

axios.post('/api/pdfs/create', body)
.then(() => axios.get('/api/pdfs/fetch', { responseType: 'blob' }))
.then((res) => {
const pdfBlob = new Blob([res.data], { type: 'application/pdf' });

return saveAs(pdfBlob, 'questions.pdf');
})
.catch(error => {
console.log(error.response)
});
}
addQuestion() {
this.setState({
questions: [...this.state.questions, '']
});
}
removeQuestion(index) {
this.setState({
questions: this.state.questions.filter((question, i) => i !== index)
});
}
render() {
return (
<div>
<button onClick={this.addQuestion}>Add Question</button>
<form onSubmit={this.handleForm}>
{this.state.questions.map((question, index) => (
<div key={index}>
<input type="text" name={`question-${question}`} onChange={(e) => this.onChange(e, index)} />
<button type="button" onClick={() => this.removeQuestion(index)}>x</button>
</div>
))}
<button type="submit">Submit</button>
</form>
</div>
);
}
}

export default Form;

最佳答案

您仅在 onChange 调用中改变状态,并且可以轻松修复:

 onChange(e, i) {        
this.setState({
questions: this.state.questions.map((v, i2) => i === i2 ? e.target.value : v),
});
}

(虽然这不会改变功能,它只是一个“最佳实践改进”)

关于javascript - React - 动态添加输入而不改变状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56138786/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com