如何在react

时间:2019-02-18 10:00:53

标签: javascript reactjs typescript

我正在尝试将表单值放入对象中,但无法将表单中的值放入地址对象中,

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 })

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

您似乎想更改state.address[ev.target.name]而不仅仅是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 };
  });
};

答案 1 :(得分:0)

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

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