[英]Require a specific type of functional component as a prop in React with Typescript
假設您有一個組件樹,例如:
function Parent(props: { componentProp: ReactElement }) {
return (
<>
{props.componentProp}
</>
);
}
function ChildA(props: { message: string }) { return (<h1>{props.message}</h1>) }
function ChildB(props: { message: string }) { return (<h2>{props.message}</h2>) }
function App() {
return (
<Parent componentProp={<ChildA message="hi"/>}
);
}
如所寫,您可以在componentProp
中將ChildA
替換為 ChildB 並且ChildB
不會抱怨。
是否可以限制componentProp
的類型,使您只能傳遞ChildA
,而傳遞ChildB
會引發類型錯誤?
任何呈現的 JSX 的類型總是相同的——我不知道有什么方法可以區分它們。 即使你這樣做,呈現的 JSX 類型也不受 function 返回類型的影響:
type Valid = ReactElement & { __valid: true }
function ChildA(props: { message: string }): Valid {
const result = <h1>{props.message}</h1>
return { ...result, __valid: true } // fails
}
const ca = <ChildA message="foo"/> // still ReactElement
但是,您可以區分組件函數本身,並將它們作為道具而不是渲染版本傳遞。 如果有效組件具有不同的道具,那么您可以擺脫它,否則您可以添加垃圾道具或垃圾返回 object 屬性:
export default null
type Valid = (props: unknown) => ReactElement & { _valid: null }
// option 1:
const A = () => {
const result = <></>
return { ...result, _valid: null }
}
// option 2:
const B = (() => <></>) as unknown as Valid
const C = () => <></>
function Parent({ Child }: { Child: Valid }) {
return <><Child /></>
}
function App() {
return (
<>
<Parent Child={A} /> {/*passes*/}
<Parent Child={B} /> {/*passes*/}
<Parent Child={C} /> {/*fails*/}
</>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.