使用HOC时在子函数中获取道具

时间:2019-06-21 20:51:18

标签: javascript reactjs

我正在尝试创建一个可以处理某些功能的HOC,并且正在创建我的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);

我无法在内部函数中获得道具,是否有这种行为的原因?

1 个答案:

答案 0 :(得分:1)

问题在于称为subFunction的函数的参数是外部范围的影子变量,然后调用subFunction时不带任何参数。