类型 IntrinsicAttributes 和 string[] 上不存在属性“props”

问题描述 投票:0回答:1

我不确定为什么会收到错误:

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>
  )
}
javascript reactjs typescript
1个回答
11
投票

您的行

<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(  // ...
}
© www.soinside.com 2019 - 2024. All rights reserved.