【发布时间】:2018-06-15 12:56:50
【问题描述】:
对于 React 的 typescript 和静态类型来说是超级新手,所以
鉴于我有这个父组件:
interface ParentProps {
something: string
}
interface ParentState {
somethingElse: string
}
export default class ParentComponent extends React.Component<ParentProps, ParentSate> {
// Component Logic.
sharedFunction() {
// Some shared function.
}
}
如何在子组件上声明不同的 props 和 state,例如:
interface ChildProps {
something: string
}
interface ChildState {
somethingElse: string
}
export default class ChildComponent extends ParentComponent<ChildProps, ChildState> {
// Child component logic.
}
当我尝试上述方法时,我得到:
[ts] Type 'ParentComponent' is not generic.
那么,实现这种分离的最佳方法是什么?谢谢。
【问题讨论】:
-
一般来说不建议你扩展自定义的 React 组件,建议你使用组合而不是继承。那里有关于原因的信息。这是官方 React 文档中关于用组合替换继承的页面:reactjs.org/docs/composition-vs-inheritance.html
-
谢谢@Jayce444 我已经阅读了文档,并且我确实相信我应该首先解决我原来的问题。
标签: reactjs typescript