提交后react-hook-form字段刷新

IT技术 javascript reactjs react-hook-form
2022-07-23 01:01:25

我将我的 react-hook-form 字段作为孩子发送到另一个函数组件。按下提交按钮后,字段刷新,输入的值被删除。问题是什么?

CodeSandBox 示例在这里

我的文件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>
  );
}
1个回答

将您的子组件移动到它自己的组件中总是一个好主意,否则,每次重新渲染都会安装和卸载您的组件。

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