我正在学习React,并使用时钟示例。该应用是使用create-react-app . --template typescript
创建的。
我对App.tsx
进行了如下修改:
import React from 'react';
import Clock from './Clock';
function App() {
return (
<div className="App">
<Clock />
</div>
);
}
export default App;
还有我的Clock.tsx
:
import React from 'react';
import ReactDOM from 'react-dom';
class Clock extends React.Component {
render() {
return <div>{ new Date().toLocaleTimeString() }</div>
}
}
export default Clock;
// My take on tick
function tick(parent: React.Component) {
const el = <div>{new Date().toLocaleTimeString()}</div>;
ReactDOM.render(el, parent);
}
但是,它不能编译:
No overload matches this call.
The last overload gave the following error.
Argument of type 'Element' is not assignable to parameter of type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)>[]'.
Type 'Element' is missing the following properties from type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)>[]': length, pop, push, concat, and 28 more. TS2769
14 | function tick(parent: React.Component) {
15 | const el = <div>{new Date().toLocaleTimeString()}</div>;
> 16 | ReactDOM.render(el, parent);
| ^
我认为将JSX.Element
编译为ReactElement
时出现问题。其他答案表明这应该可以正常工作。我删除了该函数,并将index.tsx
修改为
const el = <div>{new Date().toLocaleTimeString()}</div>;
ReactDOM.render(el, document.getElementById('root'));
然后它确实可以编译。
如何修复我的功能?
答案 0 :(得分:2)
问题是您的parent
。它的类型应该为HTMLElement
,可以由document.getElementById('root')
获得,而不是JSX.Element
或React.Component
如果您尝试的示例:
function tick(parent: HTMLElement | null) {
const el = <div>{ new Date().toLocaleTimeString() }</div>;
ReactDOM.render(el, parent);}
setInterval(() => {
tick(document.getElementById('root'))
}, 1000);
在这种情况下,您不需要计时。