我不确定为什么会收到错误:
TypeScript error in /home/amanuel2/tutorial/go/react-go/src/frontend/src/App.tsx(34,15):
Type '{ props: string[]; }' is not assignable to type 'IntrinsicAttributes & string[]'.
Property 'props' does not exist on type 'IntrinsicAttributes & string[]'. TS2322
代码:
function App() {
const [ChatHistory, setChatHistory] = useState<string[]>([])
useEffect(() => {
connect((msg: string) => {
console.log("New Message")
setChatHistory([...ChatHistory, msg])
})
console.log(ChatHistory)
return () => { }
}, [])
return (
<div className="App">
<Header />
<header className="App-header">
<Chat props={ ChatHistory }/>
<button type="submit" onClick={()=>sendMsg("Hello")}>
Hello
</button>
</header>
</div>
);
}
还有
const Chat = (props: string[]) => {
const msgs = props.map((msg:any, idx:any) => (
<p key={ idx }>
{ msg }
</p>
))
return (
<div className="ChatHistory">
<h3> Chat History </h3>
{ msgs }
</div>
)
}
您的行
<Chat props={ ChatHistory }/>
将类型{ props: string[] }
作为第一个参数(称为props
)传递到Chat
组件中,但Chat
期望它是string[]
(来自const Chat = (props: string[]) => {
)。
相反,您可以更改聊天道具的预期类型:
const Chat = (props: {props: string[]})
现在,这不是一个好的样式,因为名称
props
只能用于指定该对象中的所有属性。
因此,您可以重命名传递给聊天的 ChatHistory
属性:
render() {
// ...
<Chat chatHistory={ChatHistory}/>
}
// ...
const Chat = (props: {chatHistory: string[]}) {
props.chatHistory.map( // ...
}