未捕获的不变违规:目标容器不是DOM元素

时间:2019-02-22 18:36:03

标签: javascript html reactjs babeljs

这是我创建复选框输入样式的组件。 一切运行正常,但是有此错误消息,我不知道为什么。

“未捕获的不变违规:目标容器不是DOM元素。”

Stackoverflow要求我在提交此问题之前先发布更多评论,但实际上我没有更多信息可在此处设置...所以我将在此问题后发布我正在使用的版本。

反应版本:React v16.8.3

React DOM版本:React v16.8.3

通天塔:https://unpkg.com/babel-standalone@6.15.0/babel.min.js

    /* global ReactDOM, React */

    class Switch3dPermissao extends React.Component {

      constructor(props) {
        super(props);
        this.state = { checked: props.defaultChecked };
      }

      toggle = () => {
        this.setState({
          checked: !this.state.checked
        })
      }

      render() {

        return (
          <div>
            <label className={'mr-3 switch switch-3d switch-'+this.props.type}>
              <input type="hidden" name={this.props.id} value={this.props.offvalue} />
              <input
                id={this.props.id}
                name={this.props.id}
                value={this.props.value}
                className="switch-input"
                type="checkbox"
                checked={ this.state.checked ? true : false }
                onChange={ this.toggle }
              />
              <span className="switch-label"></span>
              <span className="switch-handle"></span>
            </label>
            <label htmlFor={ this.props.id } className="cursor-pointer" dangerouslySetInnerHTML={{ __html: this.props.html }}></label>
          </div>
        );
      }
    }

    // Elementos com esta classe
    var els = document.getElementsByClassName('switch-3d-permissao');

    for (var i in els) {

      var element = els[i];

      // Is default checked?
      var isChecked = false;
      var value = '1';
      if (element.attributes !== undefined) {

        if (element.attributes.checked !== undefined) {
          isChecked = true;
        }

        if (element.attributes.value !== undefined) {
          value = element.attributes.value.textContent;
        }
      }

      var id = null;
      var type = 'danger';
      var offvalue = '0';
      if (element.dataset !== undefined) {

        // data-id (The form checkbox id)
        if (element.dataset.id !== undefined) {
          id = element.dataset.id;
        }

        // data-type warning | danger | primary | info | success
        if (element.dataset.type !== undefined) {
          type = element.dataset.type;
        }

        // Valor para quando o checkbox nao esta checado
        if (element.dataset.offvalue !== undefined) {
          offvalue = element.dataset.offvalue;
        }
      }

      ReactDOM.render(<Switch3dPermissao id={id} type={type} html={element.innerHTML} defaultChecked={isChecked} value={value} offvalue={offvalue} />, element)
    }

3 个答案:

答案 0 :(得分:1)

这是因为使用E:\projects\tele>where python C:\Users\usrname\AppData\Local\Programs\Python\Python37\python.exe E:\projects\tele>python -i Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from ctypes import * >>> CDLL("tdjson.dll") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\usrname\AppData\Local\Programs\Python\Python37\lib\ctypes\__init__.py", line 356, in __init__ self._handle = _dlopen(self._name, mode) OSError: [WinError 193] %1 is not a valid Win32 application >>> 来迭代NodeListfor..in循环还会遍历对象的不可枚举的属性,包括长度,这会给您以下错误:目标容器不是DOM元素。

要解决此问题,您可以使用for..in循环仅循环拥有其自身的属性。

for..of
/* global ReactDOM, React */

class Switch3dPermissao extends React.Component {

  constructor(props) {
    super(props);
    this.state = { checked: props.defaultChecked };
  }

  toggle = () => {
    this.setState({
      checked: !this.state.checked
    })
  }

  render() {

    return (
      <div>
        <label className={'mr-3 switch switch-3d switch-'+this.props.type}>
          <input type="hidden" name={this.props.id} value={this.props.offvalue} />
          <input
            id={this.props.id}
            name={this.props.id}
            value={this.props.value}
            className="switch-input"
            type="checkbox"
            checked={ this.state.checked ? true : false }
            onChange={ this.toggle }
          />
          <span className="switch-label"></span>
          <span className="switch-handle"></span>
        </label>
        <label htmlFor={ this.props.id } className="cursor-pointer" dangerouslySetInnerHTML={{ __html: this.props.html }}></label>
      </div>
    );
  }
}

// Elementos com esta classe
var els = document.getElementsByClassName('switch-3d-permissao');

for (var element of els) {


  // Is default checked?
  var isChecked = false;
  var value = '1';
  if (element.attributes !== undefined) {

    if (element.attributes.checked !== undefined) {
      isChecked = true;
    }

    if (element.attributes.value !== undefined) {
      value = element.attributes.value.textContent;
    }
  }

  var id = null;
  var type = 'danger';
  var offvalue = '0';
  if (element.dataset !== undefined) {

    // data-id (The form checkbox id)
    if (element.dataset.id !== undefined) {
      id = element.dataset.id;
    }

    // data-type warning | danger | primary | info | success
    if (element.dataset.type !== undefined) {
      type = element.dataset.type;
    }

    // Valor para quando o checkbox nao esta checado
    if (element.dataset.offvalue !== undefined) {
      offvalue = element.dataset.offvalue;
    }
  }

  ReactDOM.render(<Switch3dPermissao id={id} type={type} html={element.innerHTML} defaultChecked={isChecked} value={value} offvalue={offvalue} />, element)
}

请参见methods of iteration docs from MDN

答案 1 :(得分:1)

这是一个简单的示例,展示了如何从状态更改样式。

class Sample extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      test: true,
      color: 'success'
    };

    this.handleInputChange = this.handleInputChange.bind(this);
  }

  handleInputChange(event) {
    const target = event.target;
    const name = target.name;
    const value = target.checked

    this.setState({
      [name]: value,
      color: value ? 'success' : 'danger'
    });
    
  }

  render() {
    return (
      <form>
        <label>
          Test:
          <input
            name="test"
            type="checkbox"
            checked={this.state.test}
            onChange={this.handleInputChange} />
        </label>
        <ReactBootstrap.Button className='ml-3' variant={this.state.color}>Test</ReactBootstrap.Button>
      </form>
    );
  }
}

ReactDOM.render(
  <Sample />,
  document.getElementById('root')
);
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/react-bootstrap@next/dist/react-bootstrap.min.js" crossorigin></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css" crossorigin="anonymous">

<div id="root" />

答案 2 :(得分:0)

我找到了解决方案。需要检查FOR循环上的元素是否为DOM元素,如果不继续,则继续下一个。


  var els = document.getElementsByClassName('switch-3d-permissao');

  for (var i in els) {
    var element = els[i];

    // Check if it is an object
    if (typeof element !== 'object') {
      continue;
    }

    // ...
  }