我對此進行了一些研究,但我發現的所有示例都令人費解。我試圖將其歸結為最基本的元素。我也沒有找到我正在尋找的風格的例子。但我想知道我是否能夠以這種風格創建帶有子組件的自定義 React Native 組件:
function CompositeComponent(): ReactElement {
return (
<CustomParentComponent>
// ? I would like to add child elements in the normal XML style.
<CustomChildComponent />
</CustomParentComponent>
);
}
到目前為止,這是我發現如何在自定義組件中處理子元素的唯一方法:
function CompositeComponent(): ReactElement {
return (
// ? I'd like to avoid creating child elements in this style, if possible.
<CustomParentComponent childComponent={<CustomChildComponent />}>
</CustomParentComponent>
);
}
這一直是使用標準 React Native 組件(例如View和 )完成的Text,但我似乎找不到任何帶有自定義組件的示例。
CustomParentComponent為了實作這一點,我的定義需要是什么樣的?
編輯 -
我試過這個:
function CustomParentComponent(child: ReactElement): ReactElement {
return (
<CustomParentComponent>
{child}
</CustomParentComponent>
);
}
但是當我嘗試CustomChildComponent在 JSX/XML 樣式中添加時這不起作用:
function CompositeComponent(): ReactElement {
return (
<CustomParentComponent>
// ?Error? Type '{ children: Element; }' is missing the following properties from type 'ReactElement<any, string | JSXElementConstructor<any>>': type, props, keyts(2739)
<CustomChildComponent />
</CustomParentComponent>
);
}
uj5u.com熱心網友回復:
您可以定義您CustomParentComponent的接收子道具,然后您只需渲染children.
例如,考慮下面的代碼,
const CustomParentComponent = (props) => (
<View>
{props.children}
</View>
);
現在你可以將你的孩子組件傳遞給你CustomParentComponent的
<CustomParentComponent>
<CustomChildComponent />
</CustomParentComponent>
記住children更多的是React. 您可以通過簡單地列印出虛擬 dom 樹來驗證這一點。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/315126.html
上一篇:擴展遞回Typescript介面
