[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.
相关文章
- React不同版本之间需要注意的地方
- react入门-props.children
- [React] Handle React Suspense Errors with an Error Boundary
- [React Testing] Hide console.error Logs when Testing Error Boundaries with jest.spyOn
- [Recompose] Compose Streams of React Props with Recompose’s compose and RxJS
- [React] Use React.cloneElement to Modify and Add Additional Properties to React Children
- [React Router v4] Use the React Router v4 Link Component for Navigation Between Routes
- [React Testing] The Redux Store - Multiple Actions
- [React Testing] Element types with Shallow Rendering
- [React] Intro to inline styles in React components
- React资料
- React项目使用reportWebVitals做性能监控
- React组件继承,泛型写法
- [React] Setup an API Proxy in Create React App
- [React] Use React.ReactNode for the children prop in React TypeScript components and Render Props
- [Webpack 2] Optimize React size and performance with Webpack production plugins
- 在SAP WebIDE里开发一个React component