需要根据道具来选择组件。
HOC:
const HOC = (Component, propsObject) => {
const Wrapper = () => {
const onChangeHandler = (e) => {
// updating state from where above propsObject would be updated
};
return (
<Component
onChangeHandler={onChangeHandler}
{...propsObject}
/>
);
};
return Wrapper;
};
父组件:
import HOC from "./HOC";
const componentA = ({type, propsObject}) => {
let componentToBeRendered = null;
switch (type) {
case "a":
componentToBeRendered = FormA;
break;
case "b":
componentToBeRendered = FormB;
break;
}
const FinalComponent = HOC(componentToBeRendered, propsObject);
return (<HOC />);
}
现在,只要在输入字段中键入一个字符,表单就会重新呈现。