反应-动态添加输入而不改变状态

时间:2019-05-14 21:20:59

标签: javascript reactjs

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

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

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

有更好的方法吗?

谢谢

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;

1 个答案:

答案 0 :(得分:2)

您仅在onChange调用中更改状态,并且可以轻松解决该问题:

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

(尽管这不会改变功能,但这只是“最佳实践的改进”)