亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 ReactJs 中為傳遞的道具使用打字稿接口

在 ReactJs 中為傳遞的道具使用打字稿接口

回首憶惘然 2023-04-20 10:13:51
我使用打字稿創建了這個:import React, {FC} from 'react';interface Interface {    name:string,    age:number}const Home: React.FC<Interface> = (info) => {    return (        <div>            <h1>{info.name}</h1>        </div>    );};export default Home;///const info = {name:'Boris', age:45}function App() {  return (    <div className="App">      <Home info={info}/>    </div>  );}展開片段...但是我從打字稿中得到一個錯誤: Type '{ info: { name: string; age: number; }; }' is not assignable to type 'IntrinsicAttributes & Interface & { children?: ReactNode; }'.   Property 'info' does not exist on type 'IntrinsicAttributes & Interface & { children?: ReactNode; }'問題:如何避免這種情況以及它出現的原因?
查看完整描述

2 回答

?
函數式編程

TA貢獻1807條經驗 獲得超9個贊

這段代碼在這里:


interface Interface {

? ? name:string,

? ? age:number

}

const Home: React.FC<Interface> = //...

表示該組件Home需要 2 個道具:name和age。


這段代碼在這里:


<Home info={info}/>

傳入一個名為info.


所以你要么想傳入name并age作為道具:


<Home name={info.name} age={info.age}/>

或者你想聲明info道具:


interface Props {

? ? info: {

? ? ? ? name:string,

? ? ? ? age:number,

? ? }

}

const Home: React.FC<Props> = ({ info }) => { /* ... */ }


// Pass props like:

<Home info={info}/>

(注意({ info })解構賦值,它將infoprop the 賦值給局部變量info。)


查看完整回答
反對 回復 2023-04-20
?
慕工程0101907

TA貢獻1887條經驗 獲得超5個贊

你應該在組件中銷毀你的道具Home。


所以應該是


const Home: React.FC<Interface> = ({ info }) => {

  return (

    <div>

      <h1>{info.name}</h1>

    </div>

  );

};


查看完整回答
反對 回復 2023-04-20
  • 2 回答
  • 0 關注
  • 123 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號