我是 ReactJS 的新手,并且严重陷入困境。
我有一个自定义模式,单击按钮就会弹出。该模式包含另外 2 个按钮。当我开始按选项卡按钮时出现问题。 :( 焦点移到模式屏幕后面,用户可以与应用程序交互,这是严格禁止的!
我不能为此使用 React 模式。
有没有办法使用 ReactJS/Javascript 将焦点固定在顶部的模态 div 上。 到目前为止,我已经尝试了以下方法,但似乎无法正常工作。
请看一下。任何帮助将不胜感激。
_focusRestrict() {
document.addEventListener('keydown', event => {
if (this.state.resetLifePlanner) {
//alert('Called');
event.stopPropagation();
const key = (event.keyCode ? event.keyCode : event.which);
switch (key) {
case 9:
if (document.activeElement.id === 'confirmButton') {
console.log('Called if:: move focus to cancelButton');
this.cancelButton.focus();
//React.findDOMNode(this.refs.cancelButton).focus();
//document.getElementById('cancelButton').focus();
}
else if (document.activeElement.id === 'cancelButton') {
console.log('Called else:: move focus to confirmButton');
this.confirmButton.focus();
//React.findDOMNode(this.refs.confirmButton).focus();
//document.getElementById('confirmButton').focus();
}
}
}
}, true);
}
componentDidMount() {
this._focusRestrict();
}
有ReactJS事件处理方法吗?
还有,有没有办法将事件绑定(bind)到div?
最佳答案
在event.stopPropagation();
之后,只需添加event.preventDefault();
卸载模态组件时,不要忘记删除监听器。您必须将当前的匿名函数放入命名函数中。
export default class ArtistList extends Component {
// ...
componentDidMount() {
document.addEventListener('keydown', handleKeydown, true);
}
componentWillunmount() {
document.removeEventListener('keydown', handleKeydown);
}
}
function handleKeydown(e) {
if (this.state.resetLifePlanner) {
//alert('Called');
event.stopPropagation();
event.preventDefault();
const key = (event.keyCode ? event.keyCode : event.which);
switch (key) {
case 9:
if (document.activeElement.id === 'confirmButton') {
console.log('Called if:: move focus to cancelButton');
this.cancelButton.focus();
//React.findDOMNode(this.refs.cancelButton).focus();
//document.getElementById('cancelButton').focus();
}
else if (document.activeElement.id === 'cancelButton') {
console.log('Called else:: move focus to confirmButton');
this.confirmButton.focus();
//React.findDOMNode(this.refs.confirmButton).focus();
//document.getElementById('confirmButton').focus();
}
}
}
}
关于javascript - 仅使用 ReactJS 专注于自定义模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36616709/