条件 react.js 渲染抛出错误

Conditional react.js render is throwing an error

在一个 react.js 应用程序中,我有一个 Tip 组件,它使用 Tether 库作为混入,以允许它附加到其他需要提示的组件。这很好用,但是我对如何在用户单击关闭时删除提示感到有点困惑 link。

经过一番阅读,似乎最好的做法是,从提示组件调用父级传入的方法,这不会在下一次传递时呈现组件。不幸的是,当我这样做时,我收到一条错误消息:

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>
    );
  }

});

Tether 组件

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;

根据 react docs 隐藏元素是建议的方法。