我有一个接收焦点的组件A,并传递一个onBlur处理程序。我旁边还有一个按钮。我希望onBlur for A能够做一些不同的事情,如果它在点击按钮时失去焦点而不是在DOM上的任何其他地方失去焦点 我该怎么做?
答案 0 :(得分:1)
您可以检查触发onBlur的点击DOM元素是否是按钮,如下所示:
const ComponentA = React.createClass({
propTypes: {
onBlur: React.PropTypes.func.isRequired,
},
componentDidMount: function() {
document.addEventListener('click', this.onAnyClick);
},
componentWillUnmount: function() {
document.removeEventListener('click', this.onAnyClick);
},
onAnyClick(event) {
const container = this.refs.container; // DOM element
let isClickedOutside = true; // initialization
const eventTarget = event.target; // DOM element
let elem = eventTarget;
while (elem !== null) {
if (elem === container) {
isClickedOutside = false;
break;
}
elem = elem.offsetParent;
}
if (isClickedOutside) {
this.props.onBlur(eventTarget);
}
},
render: function() {
return (
<div ref="container">
{/* component elements */}
</div>
);
},
});
const Button = React.createClass({
getElement: function() { // public method
return this.refs.element; // DOM element
},
render: function() {
return (
<input ref="element" type="button" value="Click me" />
);
},
});
const ParentComponent = React.createClass({
onComponentABlur(eventTarget) {
if (eventTarget === this.refs.button.getElement()) {
// do something if button was clicked
} else {
// do something else
}
},
render: function() {
return (
<div>
<ComponentA onBlur={this.onComponentABlur} />
<Button ref="button" />
</div>
);
},
});