我正在尝试创建一个 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/