假设我有一个名为“MyComponent”的组件,我想将它存储在 typescript 中的“MyComponent”类型的变量中,但使用 JSX 元素对其进行初始化,例如:
let comp: MyComponent = <MyComponent somePropInit={3} />
上面的代码产生如下错误:
'property 'componentDidMount' is missing in type 'Element'
我正在使用的实际组件:
export class PlayCard extends React.Component<AllCardProps, {}> {
addToDeck(){...}
我是如何尝试存储它的(我尝试过很多不同的方法,包括使用 typeof、Card.PlayCard、PlayCard 等):
import * as Card from './PlayCard'
...
let c: Card.PlayCard = <PlayCard Id={32} />
^ 如果我尝试上面的方法,我会得到一个错误
'Property 'addToDeck' is missing in type 'Component<...>'
如果我删除 addToDeck,错误将移至下一个函数。看起来存在的任何函数都会以某种方式将其关闭?
我将如何完成这个?
最佳答案
React 组件的生命周期方法是可选值。
接口(interface)示例如下:
interface ComponentLifecycle < P, S > {
/**
* Called immediately before mounting occurs, and before `Component#render`.
* Avoid introducing any side-effects or subscriptions in this method.
*/
componentWillMount ? () : void;
/**
* Called immediately after a compoment is mounted. Setting state here will trigger re-rendering.
*/
componentDidMount ? () : void;
所以错误不在 React/typescript 中。您可能使用了导致问题的界面。
引用:
- @Types/React/index.d.ts : 引用行号355.
关于javascript - 将 jsx 转换为 react 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46560665/