我對 TypeScript 還很陌生,我已經為此苦苦掙扎了一段時間。
我想將路由作為道具傳遞給組件,但我不知道如何輸入它,所以我不斷從 TypeScript 中獲取 TypeErrors。
ParentComponent(我傳遞路線的地方):
import { ChildComponent } from '../components';
export const ParentComponent = () => (
<div>
...
<ChildComponent to={"/page_one"}>text</ChildComponent>
<ChildComponent to={"/page_two"}>text</ChildComponent>
<ChildComponent to={"/page_three"}>text</ChildComponent>
...
</div>
)
然后我的子組件看起來像這樣:
import { Link } from 'react-router-dom';
interface ChildProps {
children: React.ReactNode
to?: React.LocationDescriptor<any>
}
export const ChildComponent = ({children, to}): ChildProps => {
...
<Link to={to}/>
{children}
...
}
我不斷收到錯誤訊息:“... 無法分配到型別 'LocationDescriptor | ((location: Location) => LocationDescriptor)'。”
我嘗試了多種輸入方式并四處搜索,但找不到任何適合我的解決方案。
那么,輸入“to”道具的正確方法是什么?
uj5u.com熱心網友回復:
據我所知,將型別保持為字串可以解決這個問題
type Props = { to: string; };
還要洗掉問號以確保始終傳遞該值。出于某種原因,如果您可能獲得的值可能未定義,請為其添加檢查或默認值。
希望這能回答您的疑問。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/353369.html
標籤:javascript 反应 打字稿
