Pro*_*ist 65 jsx typescript reactjs electron redux
我正在开发一个使用Typescript,React和Redux(都在Electron中运行)的项目,当我在另一个中包含一个基于类的组件并尝试在它们之间传递参数时,我遇到了一个问题.松散地说,我有容器组件的以下结构:
class ContainerComponent extends React.Component<any,any> {
..
render() {
const { propToPass } = this.props;
...
<ChildComponent propToPass={propToPass} />
...
}
}
....
export default connect(mapStateToProps, mapDispatchToProps)(ContainerComponent);
Run Code Online (Sandbox Code Playgroud)
和子组件:
interface IChildComponentProps extends React.Props<any> {
propToPass: any
}
class ChildComponent extends React.Component<IChildComponentProps, any> {
...
}
....
export default connect(mapStateToProps, mapDispatchToProps)(ChildComponent);
Run Code Online (Sandbox Code Playgroud)
显然我只包括基础知识,这两个类还有更多,但是当我尝试运行看起来像有效代码的东西时,我仍然会收到错误.我得到的确切错误:
Run Code Online (Sandbox Code Playgroud)TS2339: Property 'propToPass' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<{}, ComponentState>> & Readonly<{ childr...'.
当我第一次遇到错误时,我认为这是因为我没有通过定义我的道具的界面,但是我创建了它(如上所示)并且它仍然不起作用.我想知道,有什么我想念的吗?
当我从ContainerComponent中的代码中排除ChildComponent prop时,它渲染得很好(除了我的ChildComponent没有关键道具)但是在JSX Typescript中拒绝编译它.我认为它可能与基于本文的连接包装有关,但该文章中的问题发生在index.tsx文件中并且是提供者的问题,我在其他地方遇到了问题.
Pro*_*ist 46
因此,在阅读了一些相关的答案(特别是这一个和这个,并查看@ basarat对问题的答案后,我设法找到适合我的东西.它看起来(对于我相对较新的React眼睛),就像Connect没有提供容器组件的显式接口,因此被它试图通过的道具混淆了.
所以容器组件保持不变,但子组件改变了一点:
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);
Run Code Online (Sandbox Code Playgroud)
以上设法为我工作.显式传递组件期望从容器中获取的道具似乎工作正常,两个组件都正确呈现.
注意:我知道这是一个非常简单的答案,我不确定为什么这样做,所以如果一个更有经验的React忍者想要放弃一些关于这个答案的知识,我很乐意修改它.
Cri*_*alu 11
对我有用的只是将子组件类型从 React.FC 更改为 JSX.Element
之前(警告)
const Component: React.FC = () => {
Run Code Online (Sandbox Code Playgroud)
之后(无警告)
const Component = (): JSX.Element => {
Run Code Online (Sandbox Code Playgroud)