打字稿中反应组件中道具的简洁易读语法

concise and readable syntax for props in a react component in typescript

所以如果你声明一个 React.FC ,那么你就可以做一个类型声明并因此可以传递它 props :

const FuntionalComponent: React.FC<personType> = ({ id, nationality, name, familyName, age, selected }) =>

    <div>
       ...directly html
    </div>

export default FuntionalComponent;

但是你不能在那里声明任何方法或使用钩子(我还没有找到方法)

然后是 React.Component 类型:

class Component extends React.Component<{}, {Stateproperty: string}>{

  constructor(){
  }

  hook(){
  }

  method(){
  }

  render() {
    return (
      <div>
         ...html finally
      </div>
    )
  }
}

export default component;

如你所见,我可以传递状态但不能传递道具。

如果我尝试这样的事情:

class Component extends React.Component<{propsProperty: Array}, {Stateproperty: string}>{

然后将我的 propsProperty 添加到我的 html :

<Component propsProperty={thisArray} />

然而,他们错误地输入了以下条目:

TS2322: Type '{ propsProperty: any; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'.   Property 'tankData' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'.

这些教程似乎表明没有其他方法来声明组件:

https://riptutorial.com/reactjs/example/25321/declare-default-props-and-proptypes https://medium.com/@cristi.nord/props-and-how-to-pass-props-to-components-in-react-part-1-b4c257381654

我找到了这篇关于 React 中的 TypeScript 错误的文章: https://medium.com/innovation-and-technology/deciphering-typescripts-react-errors-8704cc9ef402,但它没有我的问题。

我也试过这个解决方案:。尽管这显然不是同一个问题,但似乎有些接近,但没有帮助。

React 文档没有帮助,因为它们忽略了 TypeScript 并且不是人类可读的。

我需要一种既简洁又尊重 TypeScript 并允许在 class 体内使用道具和方法的方法。这根本不存在吗?

But you cannot declare any methods or use hooks there (I have not found a way)

声明 FC 的一个很好的标准方法是:

type ComponentProps = {
  id: string, 
  nationality: string, 
  ...
}

const MyComponent: React.FC<ComponentProps> = ({
  id, 
  nationality, 
  ...rest
  }: ComponentProps) => {
  
  const someMethod = () => {
    console.log('I am console logging');
  }


  return(
    <div>
      {/* HERE YOU WILL RENDER STUFF */}
    </div>
  )
}

请注意,在上面我解构了实例化的道具,以便 idnationality 可以直接在组件中使用。

我认为在您熟悉上述内容之前,您不必太担心语法高亮显示。