interface IChildComponentProps extends React.Props<any> {
propToPass: any
}
class ChildComponent extends React.Component<IChildComponentProps, any> {
...
}
....
export default connect(mapStateToProps, mapDispatchToProps)(ChildComponent);
显然我只包括基础知识,这两个类都还有更多,但是当我尝试运行像有效代码的我外观时,我仍然会遇到错误。我遇到的确切错误:
TS2339: Property 'propToPass' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<{}, ComponentState>> & Readonly<{ childr...'.
当我第一次遇到错误时,我认为这是因为我没有传递定义道具的界面,但是我创建了(如上所述),但仍然不起作用。我想知道,我缺少什么吗?
的连接包装有关,但是该文章中的问题发生在index.tsx文件中,并且是提供商的问题,我在其他地方遇到问题。当我将ChildComponent Prop从ContainerComponent中的代码中排除时,它使得很好(除了我的ChildComponent没有关键的道具,但在JSX Typescript中使用它,拒绝将其编译。我认为这可能与基于文章
在阅读了一些相关的答案之后(特别是thisOne和ThisOne,然后看 @Basarat对问题的答案,我设法找到了对我有用的东西。它看起来(对我的相对较新的React Eyes),就像连接没有向容器组件提供显式接口,因此它试图通过的道具混淆了
因此,容器组件保持不变,但是子组件有些变化:interface IChildComponentProps extends React.Props<any> {
... (other props needed by component)
}
interface PassedProps extends React.Props<any> {
propToPass: any
}
class ChildComponent extends React.Component<IChildComponentProps & PassedProps, any> {
...
}
....
export default connect<{}, {}, PassedProps>(mapStateToProps, mapDispatchToProps) (ChildComponent);
上面为我工作。明确地通过容器所期望的组件似乎可以正常工作,并且两个组件都正确地呈现。 注:我知道这是一个非常简单的答案,我不确定为什么会起作用,因此,如果有经验的React React Ninja想放弃有关此答案的知识,我会很乐意修改它。
对我有用的是简单地将儿童组件类型从react.fc更改为jsx.element前(警告)
const Component: React.FC = () => {
(无警告)
const Component = (): JSX.Element => {
双重检查新添加的对象类型。当对象类型不完全符合预期的情况时。 组件中提到的Prop的类型必须与传递给该组件的Prop类型匹配。
在我的情况下,我正在建立一个打字稿组件,该组件导入了使用
connect
的JavaScript中的组件。
这里是我解决错误的快速方法。// User is a javascript component
import _User from "./User";
// Inject types that this component accepts
const User = _User as unknown as React.JSXElementConstructor<{
userId: string
}>;
const UserProfile = () => {
const user = useCurrentUser();
return (
<div className="flex items-center justify-center">
<User userId={user.userId} />
</div>
);
}
将您的子组件与您想要的类型或“任何”类型进行扩展react.com。例如:“extends React.Component<any> {...}
”
在父级组件中,您可以传递值,例如:
renderSquare(i: Number) { return <ChildComponent value={i}/>; }
检查Https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/class_components/
有关更多信息
在我的情况下,修复程序是为
React.FC
设置通用类型
interface SearchActionProps {
onClick: () => void
}
戈尔代码,给我
"Property does not exist on type 'IntrinsicAttributes'"
:
:
export const SearchActionButton: React.FC = ({onClick}: SearchActionProps) => {
...
}
export const SearchActionButton: React.FC<SearchActionProps> = ({onClick}) => {
...
}
可能是通过复制ChildComponent返回语句中的某些属性而引起的。我有重复的“样式”属性(我认为在删除一个方面解决了类似的错误)...instead,更喜欢
export default connect(mapStateToProps, mapDispatchToProps)(ChildComponent);
装饰器https://github.com/alm-tools/alm/blob/00f2f94efd3810af8a80a49f968c2ebdeb9555399/
connect
Where connect is defined here
https://github.com/alm-tools/alm/blob/00f2f94efd3810af8a80a49f968c2ebdeb955399/src/typings/react-redux/react-redux.d.ts#L6-L36
为什么?