简体   繁体   English

如何在反应功能组件中创建高阶功能

[英]How to create higher order function in react functional component

I am trying to create a HOC using react functional component that will take a component and some props, but I think I am missing something I did not get the props value in the component which I passed.我正在尝试使用 react 功能组件创建一个 HOC,该组件将采用一个组件和一些道具,但我认为我遗漏了一些我没有在我传递的组件中获得道具值的东西。 I am also using typescript我也在使用打字稿

My higher-order component:我的高阶组件:

interface EditChannelInfo {
  Component: any;
  setIsCollapsed: Function;
  isCollapsed: boolean;
}

const EditChannelInfo = (props: EditChannelInfo): ReactElement => {
  const {isCollapsed, setIsCollapsed, Component} = props;
  const {data: gamesList} = useGamesList();
  
  const games = gamesList.games.map((list: GamesList) => ({
    value: list.gameId,
    label: list.gameName,
  }));


  return <Component {...props} />;
};

export default EditChannelInfo;

From here I am passing the component to the higher-order component从这里我将组件传递给高阶组件

import EditChannelInfoWrapper from '../EditChannelInfoWrapper';

const Dashboard: NextPage = (): ReactElement => {
  const [isCollapsed, setIsCollapsed] = useState<boolean>(false);

  return (
    <div>

      <EditChannelInfo
        Component={EditChannelInfoWrapper}
        setIsCollapsed={setIsCollapsed}
        isCollapsed={isCollapsed}
      />
    </div>
  );
};

export default Dashboard;

I am getting games undefined我得到未定义的游戏

interface EditChannelInfoWrapper {
  games: any;
}

const EditChannelInfoWrapper = (
  props: EditChannelInfoWrapper,
): ReactElement => {
  const {
    games,
  } = props;
  console.log(games);
  return ()
}

It looks like you're not passing your games prop to the Component here: <Component {...props} /> .看起来您没有在这里将games道具传递给Component<Component {...props} />

Add in your games prop and it should work as expected <Component {...props} games={games} />添加您的游戏道具,它应该可以按预期工作<Component {...props} games={games} />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM