【发布时间】:2020-07-26 03:47:24
【问题描述】:
所以如果你声明一个 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: 类型 '{ propsProperty: any; }' 不可分配给类型 'IntrinsicAttributes & { children?: ReactNode; }'。财产 类型“IntrinsicAttributes & { children?”上不存在“tankData”: 反应节点; }'。
这些教程似乎表明没有其他方法可以声明组件:
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,但这不是我的问题。
我也试过这个解决方案:https://stackoverflow.com/a/47395464/4770754。尽管这显然不是同一个问题,但似乎有些接近,但没有帮助。
React 文档没有帮助,因为它们忽略 TypeScript 并且不可读。
我需要一种既简洁又尊重 TypeScript 并允许在类体内同时使用道具和方法的方法。这根本不存在吗?
【问题讨论】:
标签: reactjs typescript react-component