简体   繁体   中英

how to get form values into state object in react

I'm trying to get the form values into an object but I can not get the values from form into the address object,

this.state = {
        address: {
            country: "",
            street: "",
            postcode: "",
            city: "",
        }
}


handle_form_input = ev => {
    debug("handle_form_input", ev)
    this.setState({
        [ev.target.name]: ev.target.value
    } as Form)
}

                   K(FormField, {
                        p, s,
                        type: "text",
                        name: "firstname",
                        onInput: this.handle_form_input
                   }),
                   K(FormField, {
                        p, s, type: "text", name: "country", onInput: this.handle_form_input
                    }),

                    K(FormField, {
                        p, s, type: "text", name: "street", onInput: this.handle_form_input
                    }),

                    K(FormField, {
                        p, s, type: "text", name: "plz", onInput: this.handle_form_input
                    }),

                    K(FormField, {
                        p, s, type: "text", name: "city", onInput: this.handle_form_input
                    }),

                    K("input", { type: "submit", hidden: true })

any help would be appreciated.

It looks like you want to alter state.address[ev.target.name] and not just state[ev.target.name]

handle_form_input = ev => {
  const { name, value } = ev.target;
  this.setState(prevState => {
    const address = { ...prevState.address };
    address[name] = value;
    return { address };
  });
};

您做得很好,将所有值及其表单名称一起推送,但是状态对象上的那些表单名称包含在地址对象内,因此前进的方向是将这些值推送到表单中时应该说找到的值名称在地址对象上如下

    this.setState({address[ev.target.name]: ev.target.value})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM