在react.js应用程序中,我有一个Tip
组件,它使用Tether库作为mixin,允许它连接到需要提示的其他组件。这很好用,但是当用户点击关闭链接时,我对如何删除提示感到有些困惑。
经过一些阅读后,似乎最好的做法是从tip组件调用来自父对象的passsed方法,这将不会在下一次传递时呈现组件。不幸的是,当我这样做时,我收到一条错误消息:
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;