当在对话框-材料UI中按下按钮时,重点关注文本字段不起作用



我的目标是在通过单击对话框中的按钮关闭对话框后,将焦点设置在Material UI TextField上。

当我从一个不在对话框组件中的按钮调用它时,以下代码可以工作:

focusTitle = () => {
this.setState({ isOpen: false });
this.myRef.current.focus();
};

按钮代码:

<Button onClick={this.focusTitle} />

我想关注的文本字段代码:

<TextField
inputRef={this.myRef}
label="Title"
id="title"
multiline
rowsMax="4"
value={this.state.title}
autoFocus={true}
className={classes.title}
helperText="Enter a catchy title"
onChange={e => this.onTitleChange(e.target.value)}
/>

但是,一旦我尝试从对话框中的按钮调用focusTitle((,它就不会触发焦点。

对话框代码:

<Dialog
open={this.state.isOpen}
onClose={this.focusTitle}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
<DialogTitle id="alert-dialog-title">{"Warning"}</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-description">
Warning Message!
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={this.focusTitle} color="primary">
OK
</Button>
</DialogActions>
</Dialog>

有人知道为什么我的.focus((在对话框的情况下不起作用吗?如果我在这两种情况下都记录this.refs.myRef,它会显示完全相同的结果。

谢谢!

您的对话框可能有一个关闭动画。只要动画正在运行,就不会正确调用focus()函数。

要防止这种情况,请为动画创建回调或为动画持续时间创建超时,以便在之后触发focus()。像这样:

focusTitle = () => {
this.setState({ isOpen: false });
setTimeout(
function() {
this.myRef.current.focus();
}
.bind(this),
500 // Change to duration of the animation
};

最新更新