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

ama*_*el2 6 javascript typescript reactjs

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

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
Run Code Online (Sandbox Code Playgroud)

代码:

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>
  );
}
Run Code Online (Sandbox Code Playgroud)

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>
  )
}
Run Code Online (Sandbox Code Playgroud)

小智 10

您的行将<Chat props={ ChatHistory }/>类型{ props: string[] }作为第一个参数(称为props)传递到Chat组件中,但Chat期望它是string[], (来自const Chat = (props: string[]) => {)。

相反,您可以更改聊天道具的预期类型:

const Chat = (props: {props: string[]})
Run Code Online (Sandbox Code Playgroud)

现在,这不是一个好的样式,因为名称props只能用于指定该对象中的所有属性。因此,您可以重命名ChatHistory传递给 Chat 的 prop:

render() {
  // ...
  <Chat chatHistory={ChatHistory}/>
}

// ...
const Chat = (props: {chatHistory: string[]}) {
  props.chatHistory.map(  // ...
}
Run Code Online (Sandbox Code Playgroud)