React children用法

1. react element作为child

 <Menu>
   <Item>menu one</Item>
   <Item>menu two</Item>
 </Menu>

const Item = (props) => <li>{props.children}</li>

class Menu extends Component {
  render () {
    return (
      <ul>{this.props.children}</ul>
    )
  }
}
children基本用法

2. 函数作为child

<Container>
  {(text) => <div>{text}</div>}
</Container>

class Container extends Component {
  render () {
    return (
      <div>
        {this.props.children('hello world')}
      </div>
    )
  }
}

通过函数的方式子组件<div>..</div>就能接收父组件(Container)传给他的值,相对于直接使用<Container><div>hello world</div></Container>这样更加灵活。
childrenk可以是任意的数据结构可以是array, function, object, text, dom, react component等。

3. React.children.map

遍历props.children可以获取子组件实例,然后clone子组件进行操作,可以添加修改子组件的props如:

React.Children.map(this.props.children, (child) => {
   return React.cloneElement(child, {
       className: 'xxx',
   });
})
React.Children.map(this.props.children, (child, index) => {
    if(child.props.active) {
       return child;
    }
})

注意: 使用this.props.children.map进行遍历如果children是函数/单个react元素/对象等将会抛出错误,但是使用React.Children.map就不会

4. React.Children.forEach

使用方式和 React.children.map类似就是没有返回值。

5. React.Children.count

用于统计子元素的个数,使用方式React.Children.count(this.props.children)

<ChildrenCounter>
   {() => <h1>First</h1>}
   Second!
   <p>Third!</p>
  </ChildrenCounter>
// 返回2

注意:使用 this.props.children.length 等于 map / froreach方法中遍历次数, 函数作为child是不会遍历的

6. React.Children.toArray

如果children只包含一个函数,React.Children.toArray将返回一个空数组[ ]

React.Children.toArray(this.props.children)

使用该方法后,就可以调用数组的任意方法了,如sort,splic等对children进行操作

7. React.Children.only

验证this.props.children只包含一个React element, 所以只有当this.props.children是个React element而不是数组/单个字符串/单个函数才能返回正确的值。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.Typescript中的&理解 参数中的 & 表示props对象同时拥有了TagManagementState...
    Lethe35阅读 7,682评论 0 1
  • 自己最近的项目是基于react的,于是读了一遍react的文档,做了一些记录(除了REFERENCE部分还没开始读...
    潘逸飞阅读 3,487评论 1 10
  • 最近看了一本关于学习方法论的书,强调了记笔记和坚持的重要性。这几天也刚好在学习React,所以我打算每天坚持一篇R...
    gaoer1938阅读 1,719评论 0 5
  • 有的人觉得,不安逸,一辈子简直白活了;有的人觉得,不折腾,一辈子简直白活了。没有高低之分,看你喜欢什么。 我的同学...
    兕髑阅读 421评论 0 0
  • 恐慌和狂热都是极端的心理现象。这并不是说普通条件下不会在某些时候导致价格急剧下跌,或在某些时候导致同样急剧的上涨。...
    bigbigbigblue阅读 481评论 0 0