将子组件作为父组件的函数的参数传递并尝试呈现不起作用
//React Container Component
//Import Both Views and Render based on preference
import PosterView from "./PosterView"
import ListView from "./ListViewCard"
...
renderCardsBasedOnType(cardType){
if(cardType === "poster"){
return this.renderCards(PosterView)
}else{
return this.renderCards(ListViewCard)
}
}
renderCards(component){
let cards = this.props.list.map(function(cardData){
return <component data={cardData}/>
})
return cards
}
render(){
let cards = this.renderCardsBasedOnType("poster")
return <div>{cards}</div>
}
......
Run Code Online (Sandbox Code Playgroud)
Dam*_*oux 30
尝试Component
而不是component
.React需要一个用于jsx标记的upperCase:
renderCards(Component){
let cards = this.props.list.map(function(cardData){
return <Component data={cardData}/>
})
return cards
}
Run Code Online (Sandbox Code Playgroud)
感谢 Damien 的回答,这是使用 TypeScript 和 React 的相同答案。
相反,即没有包装器的简单组件......
export const SiteMapContent: FunctionComponent = () => {
return (
<React.Fragment>
<h1>Site Map</h1>
<p>This will display the site map.</p>
</React.Fragment>
);
}
Run Code Online (Sandbox Code Playgroud)
...您可以将组件传递到包装器中以在那里渲染,就像这样...
const renderContent: FunctionComponent<FunctionComponent> = (Foo: FunctionComponent) => {
return (
<div className="foo">
<Foo />
</div>
)
}
export const SiteMap: FunctionComponent = () => {
return renderContentOne(SiteMapContent);
}
const SiteMapContent: FunctionComponent = () => {
return (
<React.Fragment>
<h1>Site Map</h1>
<p>This will display the site map.</p>
</React.Fragment>
);
}
Run Code Online (Sandbox Code Playgroud)
同样,参数名称必须为大写,例如Foo
not foo
。
当然,另一种方式是传递一个元素而不是组件(在这种情况下参数名称不必是大写),而不是按照OP中的要求传递组件:
const renderContent: FunctionComponent<ReactElement> = (foo: ReactElement) => {
return (
<div className="foo">
{foo}
</div>
)
}
export const SiteMap: FunctionComponent = () => {
const foo: ReactElement = <SiteMapContent />;
return renderContentOne(foo);
}
const SiteMapContent: FunctionComponent = () => {
return (
<React.Fragment>
<h1>Site Map</h1>
<p>This will display the site map.</p>
</React.Fragment>
);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11708 次 |
最近记录: |