输入组件 > 提要表单组件 - 如何处理提交?

Input component > feeds Forms component - how to handle submit?

我不知道如何从 child 组件中提取输入值。

我有一个 Input 组件,我想 re-use,在那里我可以看到发生了什么 onChange,并且我看到输入的每一个变化场.

然后在 parent 组件 Form 上,我在其中使用 <Input />,我拥有带有提交按钮的表单的其余部分。在这个级别,我想处理onSubmit,但我不能see/console这里输入的值。我只能从 child.

看到它

关于我做错了什么的想法?

Input.js——这里我可以看到输入值onChange

function Input(props) {
    const { label, name, value } = props;
    const handleChange = (event) => {
        const updateForm = {...Form};
        console.log("change:", updateForm)
        updateForm[label] = event.target.value;
      }
    return (
        <label>
            {label}
            <input name={name} value={value} onChange={handleChange}></input>
        </label> 
    )
}

export { Input }

Forms.js - 这里我无法访问输入值并且submit/handle它

function Form(props) {
  
  const handleSubmit = (event) => {
    event.preventDefault();
    console.log(Input.value);
    console.log(props.label.value)
    alert(`form is: ${event.target.input}`);
  }
      return (
      <>
        <form onSubmit={handleSubmit}>
          <Input label={props.label} />
          <input type="submit" value="Submit"></input>
        </form>
      </>
    )
}

我有这个结构是因为我在主要主页组件的表单中定义了我想要的内容:

  function Home() {
  return (
    <>
        .......
        <Section withForm label={["Name"]} {...homeObjFive}/>
        <Section withForm label={"Phone"} {...homeObjOne}/>
        .......

    </>
  )
}

假设你有一个 form 有两个输入,nameemail(这些是输入的 id 属性)。您可以像这样提取表单值:

  const handleSubmit = (event) =>
  {
    event.preventDefault()
    const data = new FormData(event.currentTarget)
    const name = data.get('name')
    const email = data.get('email')
    // do something with the data
  }

您可以阅读更多关于 FormData here

这是使用 React 中的 useRef 函数的完美案例。

Form.js

import React, { useRef } from 'react'

创建一个引用常量并将其作为 prop 传递到输入组件中。并将在 onSubmit 函数中处理的输入值更改为引用

同样在Form.js(修改提交功能)

function Form(props) {

  const { inputValue } = useRef(); // added
  
  const handleSubmit = (event) => {
    event.preventDefault();
    console.log(inputValue); // changed
    console.log(props.label.value)
    alert(`form is: ${event.target.input}`);
  }
      return (
      <>
        <form onSubmit={handleSubmit}>
          {/* added the inputValue prop to the input component */}
          <Input label={props.label} inputValue={inputValue} />
          <input type="submit" value="Submit"></input>
        </form>
      </>
    )
}

现在在 Input 组件内部将 input 元素引用设置为 inputValue 属性。您将不再需要 onChange 函数,因为 useRef 函数会自动更新

Input.js

function Input(props) {
    return (
        <label>
            {props.label}
            <input name={props.name} value={props.value} ref={props.inputValue}></input>
        </label> 
    )
}

export { Input }