ReactDOM Style元素在createElement上为空

时间:2018-10-03 22:39:40

标签: reactjs jsx

由于某些原因,当尝试使用定义的样式创建元素时,会导致样式无法应用。

    const breakpointStyle = {
      height: 123,
      display: 'block',
      width: '100%',
      clear: 'both',
    };

    const breakpointElement = document.createElement(
      'div',
      { style: { breakpointStyle } },
      ' '
    );

这将导致没有样式的空div。

<div> </div>

我正在使用insertBefore插入它,并且div出现在源代码中。有什么想法我做错了吗?

1 个答案:

答案 0 :(得分:0)

我的理解是,createElement的第二个参数不应与option(作为元素的属性)以及ElementCreationOptions混淆。如果我正确理解您的问题,那就是这里发生的事情。

第二个参数需要一个字符串值,用于标识元素实例。例如,这允许您通过自定义内置元素来创建自定义元素。

对于您而言,您可以这样写:

class MyCustomDiv extends HTMLDivElement {
  constructor() {
    super();
    this.style.height = '123px';
    this.style.display = 'block';
    this.style.width = '100%';
    this.style.clear = 'both';
  }
}
customElements.define('my-custom-div', MyCustomDiv, { extends: 'div' });
const myCustomDiv = document.createElement('div', 'my-custom-div');
document.body.appendChild(myCustomDiv)

输出:

<div is="my-custom-div" style="height: 123px; display: block; width: 100%; clear: both;"></div>;

或者,一种更常见的设置属性的方式:

 const myCustomDiv = document.createElement('div');
 myCustomDiv.style.height = '123px';
 ... and so on.

这是一篇很好的文章,介绍了如何内置元素:https://www.html5rocks.com/en/tutorials/webcomponents/customelements/

但是在这篇文章中,作者指出了对Google开发人员更现代的方式: https://developers.google.com/web/fundamentals/web-components/

我希望这会对您有所帮助。