Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
824 views
in Technique[技术] by (71.8m points)

javascript - Is it possible to get the value from an input field that has been added via a button?

So I am creating a web application that allows a user to create a poll/quiz/survey etc. In the create page, I have a button that creates a new input field so the user can put in as many questions/answers as they want. Then when the user clicks the submit button it should save the values from the input fields to then be saved and sent to another page where the actual poll/quiz/survey will be created for another user to complete. How do I do this? I got this code from someone else in terms of the button that creates new input fields:

import React from 'react';
import {Form, FormInput} from 'shards-react';

class MultipleChoice extends React.Component {
    constructor(props) {
        super(props);
        this.state = { 
            inputs: ['input-0'] 
        };
    }

    appendInput() {
        var newInput = `input-${this.state.inputs.length}`;
        this.setState(prevState => (
            { inputs: prevState.inputs.concat([newInput]) }
        ));
    }

    render() {
        return(
            <div>
               <Form>
                   <div id="dynamicInput">
                       {this.state.inputs.map(input => <FormInput key={input}/>)}
                   </div>
               </Form>
               <button onClick={() => this.appendInput()}>Add Input</button>
            </div>
        );
    }
}

export default MultipleChoice;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When the user has entered all of their questions/answers you have to write the values to your state, as you are doing already with your inputs. Afterwards you should pass this information to your new component via the props. I suggest you start somewhere around here: https://reactjs.org/tutorial/tutorial.html#passing-data-through-props


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...