javascript - 使用 HOC 时在子函数中获取 props

标签 javascript reactjs

我正在尝试创建一个 HOC 来处理 React 中的一些功能,并且我正在创建我的 HOC

import React, { useState } from "react";

export default function withFormControl(WrappedComponent) {
  return props => {
    const onChangeField = e =>
      setFields({ ...fields, [e.target.id]: e.target.value });

    const [fields, setFields] = useState({});

    const submitForm = e => {
      console.log(fields);
      e.preventDefault();
    };

    return (
      <WrappedComponent
        onChangeField={onChangeField}
        submitForm={submitForm}
        fields={fields}
        {...props}
      />
    );
  };
}

我在我的组件中使用它,如下所示:

    import React, { useState } from "react";
    import { Col, Form, FormGroup, Label, Input, Button } from "reactstrap";

    import { Typo, Ico, AuthLayout } from "../../../components";

    import "./Applicant.css";
    import FormInput from "../../../components/common/FormInput/FormInput";
    import withFormControl from "../../../hocs/WithFormControl";

    function Applicant(props) {
      console.log(props); // I get the props here 
      const subFunction = props => {
        console.log(props); // returns undefined
      }
    }
    export default withFormControl(Applicant);

我无法在内部函数中获取 props,这种行为有什么原因吗?

最佳答案

问题是名为 subFunction 的函数的参数隐藏了外部作用域的变量,然后在没有任何参数的情况下调用 subFunction。

关于javascript - 使用 HOC 时在子函数中获取 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56710317/

相关文章:

javascript - Jquery ReplaceWith 保持 onclick

javascript - 导入中的 linting 错误

javascript - 设置 MUI 切换按钮组的默认值

javascript - 将状态从 ajax 从一个组件传递到另一个组件

javascript - 悬停时我的 h1 标签链接出现下划线,我没有添加

javascript - Promise - 嵌套函数不起作用

javascript - Hapi 不从 Boom 错误返回数据属性

javascript - 用于显示和隐藏多个 div 的压缩 javascript 代码

reactjs - 为什么此代码会发出有关函数作为 React 子项无效的警告?

javascript - react - 类型错误 : Cannot read property 'props' of undefined