是否可以在容器组件的函数之间传递React组件作为参数

gur*_*107 23 reactjs

将子组件作为父组件的函数的参数传递并尝试呈现不起作用

//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)

  • 哇。谢谢你!我只是浪费了两个小时,试图弄清为什么我的组件无法渲染。这样就可以了。太糟糕了,以下推荐的JS样式在这里有微妙的副作用... (2认同)
  • `renderCards(foo)` (2认同)

Chr*_*isW 5

感谢 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)

同样,参数名称必须为大写,例如Foonot 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)