我有一个关于 React 和事件处理的简单问题。我的组件看起来像这样(基本上是一个表格):
const MyList = ({ items, onBlur }) =>
<table onBlur={onBlur}}>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Publisher</th>
<th>Year</th>
<th>Author</th>
<th>System</th>
<th/>
</tr>
</thead>
<tbody>
{items.map(item => <MyListRow key={item.Id} item={item}/>)}
</tbody>
</table>;
我希望 blur
事件仅在焦点离开表格时触发。相反,当失去焦点时,事件会在表格的每个子元素上触发。
根据文档,React 让焦点事件冒泡。
问题是:如何让我的 onBlur
方法仅在焦点离开表格时触发? IOW:如何过滤掉冒出的不需要的事件,以便我只显示表明表格失去焦点的事件?
最佳答案
问题是表格实际上没有焦点的概念,因为它本身不是输入。
当 onBlur 在包含的输入上触发时,我们将检查 onBlur
事件的 relatedTarget
,该事件应设置为已获得焦点的元素(或 空
)。然后,我们使用一个函数,该函数将从该新聚焦元素向上遍历 parentNode
,并确保我们事件的 currentTarget
(表)不是新聚焦元素的祖先.如果条件通过,则假定该表不再有任何焦点。
const focusInCurrentTarget = ({ relatedTarget, currentTarget }) => {
if (relatedTarget === null) return false;
var node = relatedTarget.parentNode;
while (node !== null) {
if (node === currentTarget) return true;
node = node.parentNode;
}
return false;
}
const onBlur = (e) => {
if (!focusInCurrentTarget(e)) {
console.log('table blurred');
}
}
const MyList = ({ items, onBlur }) => (
<table onBlur={onBlur}>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Publisher</th>
<th>Year</th>
<th>Author</th>
<th>System</th>
<th/>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>
<input type="text" />
</td>
<td>
<input type="text" />
</td>
<td>
<input type="text" />
</td>
<td>
<input type="text" />
</td>
<td>
<input type="text" />
</td>
</tr>
</tbody>
</table>
);
ReactDOM.render(
<MyList onBlur={onBlur} />,
document.getElementById('root')
);
table {
padding: 10px;
border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
<br />
<input type="text" />
引用资料:
- http://www.w3schools.com/jsref/event_onblur.asp
- http://www.w3schools.com/jsref/event_currenttarget.asp
- http://www.w3schools.com/jsref/event_focus_relatedtarget.asp
- https://stackoverflow.com/a/2234986/2957138 (我们祖先检查功能的基础)
更新:
移除了对 ReactDOM.findDOMNode 的使用
关于javascript - react 和模糊事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38019140/