繁体   English   中英

条件react.js渲染抛出错误

[英]Conditional react.js render is throwing an error

在react.js应用程序中,我有一个Tip组件,该组件使用Tether库作为mixin,以便将其附加到需要技巧的其他组件上。 这很好用,但是当用户单击关闭链接时,如何删除笔尖让我有些困惑。

经过一番阅读之后,看来最佳实践似乎是从技巧组件中调用父级传递的方法,该方法不会在下一次传递时呈现该组件。 不幸的是,当我这样做时,我收到一条错误消息:

Uncaught Error: Invariant Violation: processUpdates(): Unable to find child 2 of element. This probably means the DOM was unexpectedly mutated

第一个问题是,是否有插入笔尖的更好方法? 如果您检出getTip()方法,这似乎很难做到有条件地插入组件。

第二个问题是为什么会出现上述错误。

谢谢你的帮助。

这是代码:

父组件

React.createClass({

    getTip: function() {
        if (!this.state.showTip) return React.createElement('div', null, '');

        return React.createElement(Tip, {
            closeText: 'Got it!',
            destroy: this.removeTip,
            attachment: 'top center',
            targetAttachment: 'bottom center'
          },
          'Click outer arrows to skip by the week and inner arrows to skip by the day.');
    },

    removeTip: function() {
      this.setState({showTip: false});
    },

    render: function() {
        var tip = this.getTip();

        return (
          <div className="page">
            <header>
              <div className="dates__header__details">
                <!-- stuff -->

                {tip}
              </div>
              ...   
})

尖端组件

var React = require('react');
var Tether = require('../tether/tether');

var Tip = React.createClass({

  mixins: [Tether],

  propTypes: {
    destroy: React.PropTypes.func.isRequired
  },

  getInitialState: function() {
    return {
      isVisible: true
    }
  },

  remove: function() {
    this.setState({isVisible: false});
    setTimeout(function() {
      this.props.destroy();
    }.bind(this), 500);
  },

  render: function() {
    // ...

    return (
      <div className={classList}>
        {this.props.children}

        <div className="tip__close" onClick={this.remove}>{this.props.closeText}</div>
      </div>
    );
  }

});

系链组件

var React = require('react');
var T = require('../../../../../bower_components/tether/tether');

var Tether = {

  propTypes: {
    attachment: React.PropTypes.string.isRequired,
    targetAttachment: React.PropTypes.string.isRequired
  },

  componentDidMount: function() {
    var el = this.getDOMNode();

    var tether = new T({
      target: el.parentNode,
      element: el,
      attachment: this.props.attachment,
      targetAttachment: this.props.targetAttachment
    });

    this.setState({'tether': tether});
  },

  componentWillUnmount: function() {
    var t = this.state.tether;
    t.destroy();
  }
};

module.exports = Tether;

根据反应文档,隐藏元素是建议的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM