zoukankan      html  css  js  c++  java
  • [React] Understand React.Children Utilities

    The data contained in this.props.children is not always what you might expect. React provides React.children to allow for a more consistent development experience.

    For example, you have an component:

    class App extends React.Component {
      render(){
        return (
          <Parent>
            <div className="childA"></div>
    <div className="childB"></div> </Parent> ) } }

    Inside parent component, you have two children.

    So if you log out 'this.props.children', it should be an Array.

    class Parent extends React.Component {
      render(){
        console.log(this.props.children) // Array
        return null
      }

    But things happen when 'Parent' component has only one Child:

    class App extends React.Component {
      render(){
        return (
          <Parent>
            <div className="childA"></div>
          </Parent>
        )
      }
    }

    When you log out 'this.props.children', it become an Object. So if you call '.map' on an Object, it will throw error.

    What you can do for this is using 'React.Children.map':

    let items = React.Children.map(this.props.children, (child) => console.log(child)); 

    Even there is only one Child inside parent component, it will still convert it into an Array not a Object.

    Other ways to do this such as:

    let items = React.Children.forEach(this.props.children, (child) => console.log(child)); 
    let items = React.Children.toArray(this.props.children)

    If you only want Object which means just one Child, you can use:

    let items = React.Children.only(this.props.children)

    But if 'this.props.children' contains multi children, then it will throw an error.

  • 相关阅读:
    只要三步,使用html5+js实现像素风头像生成器
    按Ctrl+Enter发送的实现
    “放到桌面”的Servlet实现
    从tom大叔那想着拿书的,呵呵。
    也写dateUtil.js
    智习室
    零基础爬虫课,不会编程也能做爬虫
    1小时教你学会如何采集微博数据:0基础小白也能轻松学会!
    TransactionScope 分布式事务配置
    centos7创建共享文件夹
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6306842.html
Copyright © 2011-2022 走看看