Javascript 如何避免在 React 中额外包装 <div>?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33766085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:27:35  来源:igfitidea点击:

How to avoid extra wrapping <div> in React?

javascriptreactjs

提问by Kirill Reznikov

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 example of what I am doing below.

今天我开始学习 ReactJS 并在一个小时后面临这个问题..我想在页面上的 div 内插入一个有两行的组件。下面是我正在做的事情的一个简化示例。

I have an html:

我有一个 html:

<html>
..
  <div id="component-placeholder"></div>
..
</html>

Render function like this:

渲染函数如下:

...
render: function() {

    return(
        <div className="DeadSimpleComponent">
            <div className="DeadSimpleComponent__time">10:23:12</div >
            <div className="DeadSimpleComponent__date">MONDAY, 2 MARCH 2015</div>
        </div>
    )
}
....

And below I am calling render:

下面我调用渲染:

ReactDOM.render(<DeadSimpleComponent/>, document.getElementById('component-placeholder'));

Generated HTML looks like this:

生成的 HTML 如下所示:

<html>
..
  <div id="component-placeholder">
    <div class="DeadSimpleComponent">
            <div class="DeadSimpleComponent__time">10:23:12</div>
            <div class="DeadSimpleComponent__date">MONDAY, 2 MARCH 2015</div>
    </div>
</div>
..
</html>

The problem that I am not a very happy that React forcing me to wrap all in a div "DeadSimpleComponent". What is the best and simple workaround for it, without explicit DOM manipulations?

我不是很高兴 React 强迫我将所有内容都包装在一个 div“DeadSimpleComponent”中。在没有显式 DOM 操作的情况下,最好和最简单的解决方法是什么?

UPDATE 7/28/2017: Maintainers of React added that possibility in React 16 Beta 1

2017 年 7 月 28 日更新:React 的维护者在 React 16 Beta 1 中添加了这种可能性

Since React 16.2, you can do this:

React 16.2 开始,你可以这样做:

render() {
  return (
    <>
      <ChildA />
      <ChildB />
      <ChildC />
    </>
  );
}

回答by Luger

This requirement was removed in React version (16.0)]1, so now you are able to avoid that wrapper.

此要求已在 React 版本 (16.0)] 1中删除,因此现在您可以避免使用该包装器。

You can use React.Fragment to render a list of elements without creating a parent node, official example:

你可以使用 React.Fragment 来渲染元素列表,而无需创建父节点,官方示例:

render() {
  return (
    <React.Fragment>
      <ChildA />
      <ChildB />
      <ChildC />
    </React.Fragment>
  );
}

More here: Fragments

更多信息:片段

回答by Tom

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

2017 年 12 月 5 日更新:React v16.2.0现在完全支持片段渲染,并改进了对从组件渲染方法返回多个子项的支持,而无需在子项中指定键:

render() {
  return (
    <>
      <ChildA />
      <ChildB />
      <ChildC />
    </>
  );
}

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

如果您使用的是 v16.2.0 之前的 React 版本,也可以使用<React.Fragment>...</React.Fragment>

render() {
  return (
    <React.Fragment>
      <ChildA />
      <ChildB />
      <ChildC />
    </React.Fragment>
  );
}


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

React v16.0 引入了在 render 方法中返回元素数组而不将其包装在 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 :)
    <li key="A">First item</li>,
    <li key="B">Second item</li>,
    <li key="C">Third item</li>,
  ];
}

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.

将来,我们可能会向 JSX 添加一个不需要键的特殊片段语法。

回答by Rolando Cintron

You can use:

您可以使用:

render(){
    return (
        <React.Fragment>
           <div>Some data</div>
           <div>Som other data</div>
        </React.Fragment>
    )
}

For further details refer to this documentation.

有关更多详细信息,请参阅此文档

回答by Matt Landers

I created a component to wrap child components without a DIV. It's called a shadow wrapper: https://www.npmjs.com/package/react-shadow-wrapper

我创建了一个组件来包装没有 DIV 的子组件。它被称为影子包装器:https: //www.npmjs.com/package/react-shadow-wrapper

回答by Michael Cuneo

Use [], instead of ()'s to wrap the entire return.

使用 [],而不是 () 来包装整个返回。

render: function() {
  return[
    <div className="DeadSimpleComponent__time">10:23:12</div >
    <div className="DeadSimpleComponent__date">MONDAY, 2 MARCH 2015</div>
  ]
}

回答by prime

This is still required, BUTReact now make sure to create elements without creating an additional DOM element.

这仍然是必需的但是React 现在确保创建元素而不创建额外的 DOM 元素。

The extra wrapping needed (normally with a parent div) because Reacts createElementmethod require a typeparameter which is either a tag name string (such as 'div' or 'span'), a React component type (a class or a function). But this was before they introduce React Fragment.

需要额外的包装(通常使用 parent div),因为 ReactscreateElement方法需要一个type参数为either a tag name string (such as 'div' or 'span'), a React component type (a class or a function). 但这是在他们引入 React 之前Fragment

Refer this NEW api doc for createElement

请参阅此新 api 文档以获取 createElement

React.createElement: Create and return a new React element of the given type. The type argument can be either a tag name string (such as 'div' or 'span'), a React component type (a class or a function), or a React fragment type.

React.createElement:创建并返回给定类型的新 React 元素。type 参数可以是标签名称字符串(例如 'div' 或 'span')、React 组件类型(类或函数)或 React 片段类型

here is the official example, Refer React.Fragment.

这是官方示例,请参阅React.Fragment

render() {
  return (
    <React.Fragment>
      Some text.
      <h2>A heading</h2>
    </React.Fragment>
  );
}

回答by erfan seidipoor

There is workaround too. The below block code generates fragment without the need of React.Fragment.

也有解决方法。下面的块代码无需 React.Fragment 即可生成片段。

return [1,2,3].map(i=>{
if(i===1) return <div key={i}>First item</div>
if(i===2) return <div key={i}>Second item</div>
return <div key={i}>Third item</div>
})

回答by Ярослав Рахматуллин

Here is one way to render "transculent" components:

这是渲染“半透明”组件的一种方法:

import React from 'react'

const Show = (props) => {
  if (props.if || false) {
    return (<React.Fragment>{props.children}</React.Fragment>)
  }
  return '';
};

----


<Show if={yomama.so.biq}>
    <img src="https://yomama.so.biq">
    <h3>Yoamama</h3>
<Show>

enter image description here

在此处输入图片说明

回答by Henrik Andersson

You won't be able to get rid of that divelement. React.render() needs to return one valid DOM node.

你将无法摆脱那个div元素。React.render() 需要返回一个有效的 DOM 节点。

回答by Gabriel P.

I know this question has been answered, you can of course use React.Fragment which doesn't create a node but let's you group stuff like a div.

我知道这个问题已经得到解答,您当然可以使用 React.Fragment,它不会创建节点,但让您将诸如 div 之类的东西分组。

Additionally if you want to have fun you can implement (and learn lots of things) a React mode that removes the extra div's and for this I really want to share a great video on how you can do it on the react code base itself.

此外,如果你想玩得开心,你可以实现(并学习很多东西)一个移除额外 div 的 React 模式,为此我真的想分享一个关于如何在 React 代码库本身上做到这一点的精彩视频。

https://www.youtube.com/watch?v=aS41Y_eyNrU

https://www.youtube.com/watch?v=aS41Y_eyNrU

This is of course not something that you would do in practice but it's a good learning opportunity.

这当然不是您在实践中会做的事情,但这是一个很好的学习机会。