简体   繁体   English

如何将反应jsx中的自定义proptype转换为typescript

[英]How to convert custom proptype in react jsx to typescript

I am converting my project files from jsx to tsx.我正在将我的项目文件从 jsx 转换为 tsx。 For normal proptypes, I am able to provide equivalent in interface.对于普通的 proptypes,我可以提供等效的接口。 But for custom Proptypes I am unable to do the same.但对于自定义 Proptypes,我无法做到这一点。 please find below the example scenario to get an idea.请在示例场景下方找到一个想法。

AppContainer.jsx应用容器.jsx

    const AppContainer = (props) => {
  return <div>{/*my component*/}</div>;
};

const customPropCheck = (props, propName, componentName) => {
  if (
    (props.primaryValue && !props.secondaryValue) ||
    (!props.primaryValue && props.secondaryValue)
  ) {
    return new Error(`Error for ${componentName} `);
  }
  return null;
};
AppContainer.defaultProps = {
  primaryValue: null,
  secondaryValue: null,
};

AppContainer.propTypes = {
  primaryValue: customPropCheck,
  secondaryValue: customPropCheck,
};

export default AppContainer;

AppContainer.tsx应用容器.tsx

interface AppContainerProps {
  primaryValue: Error | null;
  secondaryValue: Error | null;
}

const AppContainer = ({
  primaryValue = null,
  secondaryValue = null,
}: AppContainerProps) => {
  return <div>{/*my component*/}</div>;
};

export default AppContainer;

How do i implement customPropCheck in my tsx?如何在我的 tsx 中实现 customPropCheck? Is there any way Or do I have to copy same propType implementation in my tsx file ie:有什么办法或者我必须在我的 tsx 文件中复制相同的 propType 实现,即:

AppContainer.propTypes = {
    primaryValue: customPropCheck,
    secondaryValue: customPropCheck 
} 

As far as I can tell, there's no problem just doing it.据我所知,这样做没有问题。 The types of the parameters in customPropCheck are AppContainerProps , keyof AppContainerProps , and string respectively: customPropCheck中的参数类型分别为AppContainerPropskeyof AppContainerPropsstring

const customPropCheck = (props: AppContainerProps, propName: keyof AppContainerProps, componentName: string) => {
    if (
        (props.primaryValue && !props.secondaryValue) ||
        (!props.primaryValue && props.secondaryValue)
    ) {
        return new Error(`Error for ${componentName} `);
    }
    return null;
};

Then you just assign to the function (I was expecting this to be a problem, but it doesn't seem to be):然后你只需分配给 function (我原以为这是个问题,但似乎不是):

AppContainer.defaultProps = {
    primaryValue: null,
    secondaryValue: null,
};

AppContainer.propTypes = {
    primaryValue: customPropCheck,
    secondaryValue: customPropCheck,
};

Playground link 游乐场链接

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

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