简体   繁体   English

防止表单在 React 中从父级重新加载到子级

[英]Prevent form reloading from parent to child in React

I'm trying to pass data from my child component (who has the form), to the parent component using a callback function, but I can't use the event.preventDefault() from the parent function, my code is the next:我正在尝试使用回调 function 将数据从我的子组件(具有表单)传递到父组件,但我不能使用父 function 的 event.preventDefault(),我的代码是下一个:

function handleSubmit (event) {
    console.log("Done")
    event.preventDefault()
}

<LoginForm onFormSubmit={handleSubmit}/>

And this is my child form component:这是我的子表单组件:

const [currentUser, setCurrentUser] = useState({
    username: "",
    password: ""
})

function handleChange(event) {
    const {name, value} = event.target

    setCurrentUser(prevValue => {
        if (name === "email") {
            return {
                username: value,
                password: prevValue.password
            };
        } else if (name === "password") {
            return {
                username: prevValue.username,
                password: value
            };
        }
    })
}

    <form
         onSubmit={() => props.onFormSubmit()}
         className={classes.form}>
                <TextField
                    onChange={handleChange}
                    id="email"
                    label="Email Address"
                    name="email"
                    value={currentUser.username}
                />
                <TextField
                    onChange={handleChange}
                    id="password"
                    label="Password"
                    name="password"
                    type="password"
                    value={currentUser.password}
                />
                <Button
                    type="submit"
                >
    </form>

So my question is, how can I prevent the form from reloading, and how can I pass the currentUser values to the parent component, thanks in advance!所以我的问题是,如何防止表单重新加载,以及如何将 currentUser 值传递给父组件,在此先感谢!

As parent re-renders it will cause child to re-render.当父母重新渲染时,它将导致孩子重新渲染。 You can prevent this using React.memo() it does shallow comparison with previous & incoming props and determine whether to render or not.您可以使用React.memo()来防止这种情况,它会与之前的和传入的props进行浅比较,并确定是否渲染。

Example child component:示例子组件:

const ChildComp = React.memo(
   ({pristineForm}) => <div>Child component</div>
)

pristineForm is initially true if you make it false after updating parent state child will not re-render.如果在更新父 state 后将 pristineForm 设为false ,则pristineForm最初为true ,子不会重新渲染。

You are not passing event e from child component:您没有从子组件传递事件e

<form
  onSubmit={e => {
    // e.preventDefault(); 
    props.onFormSubmit(); // You didn't pass e
  }}
>
  <TextField
    onChange={handleChange}

    // .... 

</form>

but expecting it in parent's handler:但在父母的处理程序中期待它:

function handleSubmit (event) {
    console.log("Done")
    event.preventDefault()
}

So, either pass the event e from child or use e.preventDefault() in the child itself as shown above.因此,要么从子级传递事件e ,要么在子级本身中使用e.preventDefault() ,如上所示。 And to pass the form data back to parent, you should pass currentUser and handle it in parent.并且要将表单数据传递回父级,您应该传递currentUser并在父级中处理它。

  onSubmit={e => {
    e.preventDefault();
    props.onFormSubmit(currentUser);
  }}

In parent:在父母中:

function handleSubmit (data) {
    console.log("Done", data)
    // do something with data, e.g. make API call
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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