如何在功能组件之间传递状态?

IT技术 reactjs state react-hooks
2021-05-13 16:44:43

我目前正在使用带有 react-hooks 的 react-js 编写一个注册页面,我仍在学习,所以如果这是一个非常简单的问题,请原谅。

我有一个用带有钩子的功能组件编写的 signup.js。signup.js 导入 'EmailTextField', 'PasswordTextField', 'NameTextField', 'CellPhoneTextField' ... 的组件也用钩子编写在功能组件中。

我将所有这些文本字段作为单独的组件来简化代码,因为我需要对每个文本字段进行许多不同的检查。(并且在 signup.js 页面中包含所有这些字段会产生很长的代码)

在 signup.js 中的过程结束时,我想获得它所有子组件(所有这些文本字段)的状态(用户是否适合登录。)但我不知道如何通过从这些文本字段到 signup.js 的状态(或变量)。

我知道 redux 可以管理状态,但是有没有办法在没有 redux 的情况下实现这一点?

谢谢你。

用最少的示例代码创建了一个CodeSandbox 示例

在这里,我EmailTextfieldapptest.js. 我想从中获取isValid状态EmailTextfieldapptest.js以便我可以确保在用户注册之前验证所有字段。

'./components/UI/Textfield/EmailTextField.js'

import React, { useState } from "react";
import TextField from "@material-ui/core/TextField";
import Grid from "@material-ui/core/Grid";

export const EmailTextField = props => {
  const [value, setValue] = useState("");
  const [helperText, setHelperText] = useState(
    "Email address will be used as your username."
  );
  const [isValid, setIsValid] = useState("true");

  const handleOnChangeEmailAddress = event => {
    // Email Validation logic
    if (true) {
      setIsValid(true);
    } else {
      setIsValid(false);
    }
  };

  return (
    <Grid item xs={12}>
      <TextField
        variant="outlined"
        required
        fullWidth
        id="email"
        label="email address"
        error={!isValid}
        helperText={helperText}
        name="email"
        autoComplete="email"
        margin="dense"
        onBlur={handleOnChangeEmailAddress}
      />
    </Grid>
  );
};

export default EmailTextField;

'aptest.js'

import React from "react";
import CssBaseline from "@material-ui/core/CssBaseline";
import Grid from "@material-ui/core/Grid";
import { makeStyles } from "@material-ui/core/styles";
import Container from "@material-ui/core/Container";
import { EmailTextField } from "./components/UI/Textfield/EmailTextField";

const useStyles = makeStyles(theme => ({
  "@global": {
    body: {
      backgroundColor: theme.palette.common.white
    }
  },
  paper: {
    marginTop: theme.spacing(8),
    display: "flex",
    flexDirection: "column",
    alignItems: "center"
  },
  mainBox: {
    // margin: '200px',
    width: "550px",
    textAlign: "left",
    boxShadow: "0 2px 3px #ccc",
    border: "1px solid #eee",
    padding: "40px 70px 50px 70px",
    boxSizing: "border-box"
  },
  form: {
    width: "100%", // Fix IE 11 issue.
    marginTop: theme.spacing(3)
  }
}));

const Apptest = props => {
  const classes = useStyles();
  return (
    <Container component="main" maxWidth="xs">
      <CssBaseline />
      <div className={classes.paper}>
        <div className={classes.mainBox}>
          <form className={classes.form} noValidate>
            <Grid container spacing={2}>
              <EmailTextField />
            </Grid>
          </form>
        </div>
      </div>
    </Container>
  );
};

export default Apptest;
3个回答

我有一个非常粗略的实现。

输入字段周围应该有一个一致的数据模型。该数据模型应该是该特定输入字段的单一真实来源。它应该能够判断该特定字段是否被触及、是否有错误、是否原始、它的value是什么等等。

所以假设你有这样的:

errors: [],
onChange: false,
pristine: true,
touched: false,
value,

我们称之为StateChangeEvent.

现在,每个输入字段都将有一个处理诸如更改和模糊之类的事件的处理程序。在这里,单个组件将更新 StateChangeEvent。这些方法最终会调用一个回调函数StateChangeEvent作为参数。

这样,父项就会知道其中一个字段发生了变化,并且可以做出相应的响应。

在父组件中,为了启用表单上的提交按钮,我们还可以有一个副作用来更新表单的整体状态。像这样的东西:

useEffect(() => {
  const isValid = !fieldOne.onChange &&
    fieldOne.errors.length === 0 &&
    fieldOne.value.length !== 0 &&
    !fieldTwo.onChange &&
    fieldTwo.errors.length === 0 &&
    fieldTwo.value.length !== 0 &&
    ...;
  setIsFormValid(isValid);
}, [fieldOne, fieldTwo, ...]);

我确定这不是一个完整的解决方案。但我相信它会让你开始。

更新:

根据您提供的 CodeSandbox,您可以执行以下操作来完成这项工作:

import ...

const useStyles = makeStyles(theme => ({ ... }));

const Apptest = props => {

  const classes = useStyles();
  const [isInvalid, setIsInvalid] = useState(true);

  const handleStateChange = updatedState => {
    console.log("updatedState: ", updatedState);
    updatedState.errors.length === 0 ? setIsInvalid(false) : setIsInvalid(true);
  };

  return (
    <Container component="main" maxWidth="xs">
      <CssBaseline />
      <div className={classes.paper}>
        <div className={classes.mainBox}>
          <form className={classes.form} noValidate>
            <Grid container spacing={2}>
              <EmailTextField onStateChange={handleStateChange} />
            </Grid>
            <Button
              variant="contained"
              color="primary"
              disabled={isInvalid}
              className={classes.button}
            >
              Submit
            </Button>
          </form>
        </div>
      </div>
    </Container>
  );
};

export default Apptest;

EmailTextField组件中:

import React, { useState } from "react";
import TextField from "@material-ui/core/TextField";
import Grid from "@material-ui/core/Grid";

export const EmailTextField = props => {
  const { onStateChange } = props;
  const [state, setState] = useState({
    errors: [],
    onChange: false,
    pristine: true,
    touched: false,
    value: null
  });
  const helperText = "Email address will be used as your username.";

  const handleBlur = event => {
    // Email Validation logic
    const matches = event.target.value.match(
      `[a-z0-9._%+-]+@[a-z0-9.-]+.[a-z]{2,3}`
    );
    if (matches) {
      const updatedState = {
        ...state,
        touched: true,
        value: event.target.value,
        errors: []
      };
      setState(updatedState);
      onStateChange(updatedState);
    } else {
      const updatedState = {
        ...state,
        touched: true,
        value: event.target.value,
        errors: ["Please enter a valid email"]
      };
      setState(updatedState);
      onStateChange(updatedState);
    }
  };

  return (
    <Grid item xs={12}>
      <TextField
        variant="outlined"
        required
        fullWidth
        id="email"
        label="email address"
        error={state.errors.length > 0}
        helperText={state.errors.length > 0 ? state.errors[0] : helperText}
        name="email"
        autoComplete="email"
        margin="dense"
        onBlur={handleBlur}
      />
    </Grid>
  );
};

export default EmailTextField;

这是供您参考工作 CodeSandbox 示例

我想通了,抱歉回复晚了。我睡着了。基本上是onBlur()一个回调,现在在这种情况下,您需要将输入框中的值传递给回调,以便您可以访问用户输入的值。另一种方法是使用 anonChange()来跟踪更改并设置它,以便在onblur调用 时可以检查value,然后可以执行验证。

所以你只需要将target事件传递callback类似的东西onBlur={(e) => handleOnChangeEmailAddress(e.target.value)},然后你就可以访问方法中的值。我已经重构了您在沙箱中共享的代码。在下面找到我所做的片段。

import React, { useState } from "react";
import TextField from "@material-ui/core/TextField";
import Grid from "@material-ui/core/Grid";

export const EmailTextField = props => {
  const [value, setValue] = useState("");
  const [helperText, setHelperText] = useState(
    "Email address will be used as your username."
  );
  const [isValid, setIsValid] = useState("true");

  const handleOnChangeEmailAddress = value => {
    // Email Validation logic
    if (!value) {
      setIsValid(true);
    } else {
      setIsValid(false);
    }
    console.log(isValid)
  };

  return (
    <Grid item xs={12}>
      <TextField
        variant="outlined"
        required
        fullWidth
        id="email"
        label="email address"
        error={!isValid}
        helperText={helperText}
        name="email"
        autoComplete="email"
        margin="dense"
        onBlur={(e) => handleOnChangeEmailAddress(e.target.value)}
      />
    </Grid>
  );
};

export default EmailTextField;

我希望它有帮助.. 如果您有任何问题,请不要犹豫,提出问题..

从您的代码和框示例看来,您几乎就在那里,您只需要将您的onStateChange函数作为props传递

<EmailTextField onStateChange={onStateChange} />

然后onStateChange在您的apptest.js文件中实现将获得更新对象的函数。

查看下面的示例并打开控制台,如果电子邮件有效,您将看到控制台日志的错误和“isValid”响应。

https://codesandbox.io/s/loving-blackwell-nylpy?fontsize=14