简体   繁体   中英

react-hook-form field refreshes after submit

I'm sending my react-hook-form field to another function component as a children. After pressing Submit Button, the field refreshes and the value inputed is deleted. What is the problem?

CodeSandBox example is here

My file App.js :

import React from "react";
import "./styles.css";
import { useForm } from "react-hook-form";
import { Box, Button, Grid, TextField } from "@material-ui/core";

export default function App() {
  const { register, handleSubmit } = useForm();

  function onSubmit(data) {
    console.log(data);
  }

  function FieldComponent(props) {
    const { title, children } = props;
    return (
      <Grid container alignItems="center">
        <Grid item xs={3}>
          <Box py={5}>
            <div fontWeight="bold" fontSize="16">
              {title}
            </div>
          </Box>
        </Grid>
        <Grid item xs={9}>
          <Box py={5}>{children}</Box>
        </Grid>
      </Grid>
    );
  }

  return (
    <div className="App">
      <Grid container>
        <Grid item xs={12}>
          <FieldComponent title="name">
            <TextField variant="outlined" name="name" inputRef={register} />
          </FieldComponent>
        </Grid>
        <Grid item xs={12}>
          <Button variant="outlined" onClick={handleSubmit(onSubmit)}>
            Submit
          </Button>
        </Grid>
      </Grid>
    </div>
  );
}

It's always a good idea to move your sub-component into its own, otherwise, each re-render will mount and unmount your component.

function FieldComponent(props) {
  const { title, children } = props;
  return (
    <Grid container alignItems="center">
      <Grid item xs={3}>
        <Box py={5}>
          <div fontWeight="bold" fontSize="16">
            {title}
          </div>
        </Box>
      </Grid>
      <Grid item xs={9}>
        <Box py={5}>{children}</Box>
      </Grid>
    </Grid>
  );
}

export default function App() {
  const { register, handleSubmit } = useForm();

  function onSubmit(data) {
    console.log(data);
  }

  return (
    <div className="App">
      <Grid container>
        <Grid item xs={12}>
          <FieldComponent title="name">
            <TextField variant="outlined" name="name" inputRef={register} />
          </FieldComponent>
        </Grid>
        <Grid item xs={12}>
          <Button variant="outlined" onClick={handleSubmit(onSubmit)}>
            Submit
          </Button>
        </Grid>
      </Grid>
    </div>
  );
}

https://codesandbox.io/s/agitated-darkness-leg7z?file=/src/App.js

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