How to avoid extra wrapping
in React?

前端 未结 10 988
孤独总比滥情好
孤独总比滥情好 2020-12-02 12:04

Today I have started learning ReactJS and after an hour faced with the problem.. I want to insert a component which has two rows inside a div on the page.A simplified exampl

10条回答
  •  情深已故
    2020-12-02 12:09

    Update 2017-12-05: React v16.2.0 now fully supports rendering of fragments with improved support for returning multiple children from a components render method without specifying keys in children:

    render() {
      return (
        <>
          
          
          
        
      );
    }
    

    If you are using a React version prior to v16.2.0, it is also possible to use ... instead:

    render() {
      return (
        
          
          
          
        
      );
    }
    

    Original:

    React v16.0 introduced returning an array of elements in render method without wrapping it in a div: https://reactjs.org/blog/2017/09/26/react-v16.0.html

    render() {
      // No need to wrap list items in an extra element!
      return [
        // Don't forget the keys :)
        
  • First item
  • ,
  • Second item
  • ,
  • Third item
  • , ]; }

    At the moment, a key is required for each element to avoid the key warning but this could be changed in future releases:

    In the future, we’ll likely add a special fragment syntax to JSX that doesn’t require keys.

提交回复
热议问题