美文网首页
将React 组件作为props传入组件

将React 组件作为props传入组件

作者: 张培_ | 来源:发表于2018-08-29 21:02 被阅读648次

React中有很多方法可以进行组件的复用。比如HOC、FACC等等,为了提高组件的复用性,也可将组件作为props 传递给组件。

传递组件的实例

类似于props.children的方式传递组件

  • 方式: 使用children传参component的方式。
const Label = props => <div>{props.children}</div> 

const Tag = props => <div>This is tag</div>

const Page = props => <Label><Tag /></Label>

非children属性传递组件实例

将组件实例化之后作为属性传递给父组件

const Label = props => <div>{props.content}</div> 

const Tag = props => <div>This is tag</div>

const Page = props => <Label content={<Tag />}/>

传递组件的定义

传递的组件是有状态或者无状态组件

  • 注意: 定义组件作为变量的时候,变量的命名一定需要用大写字母开头!!

  • 原因: React中使用<>包裹的变量名字必须使用大写字母开头

const Label = props => {
    const Tag = this.props.tag;
    //必须申明为大写
    return <span><Tag /></span> 
}

const Tag = () => <span>this is tag!</span> 
const Page = props => (
    <div><Label tag={Tag}/></div>
)

传递的组件是无状态组件

前提:被作为props的component其必须是使用function的方式定义,代码中只需要拿出props,然后调用一下即可(使用这种方式可以传递props)。

const Label = props => <div>{props.tag()}</div> 

const Tag = props => <div>This is tag</div>

const Page = props => <Label tag={Tag}/>

扩展 render prop

最后一种方式,类似于React社区中提出的render props 方法,同样是为了提高组件的复用性,可以在使用组件的时候自定义组件的渲染方式。

const Label = props => <div>{props.render(props.name)}</div> 

const Page = props => <Label render={(props)=> <div>{props}</div>}/>
  • 可以在任何使用Label组件的Component中自定义render props的内容,从而达到对Label组件的复用
  • 随手定义的render方法对应的组件可以随意使用Label中的props、或者state

相关文章

网友评论

      本文标题:将React 组件作为props传入组件

      本文链接:https://www.haomeiwen.com/subject/lfflwftx.html