繁体   English   中英

在MUI输入组件的区域之外单击时,将焦点放在MUI输入组件上

[英]Setting focus on an MUI Input component when clicking outside its area

我正在用ReactJS和Material UI创建一个应用程序。 我在FormControl组件内有一个Input组件。 当用户单击FormControl(但仍在Input组件之外)时,我想将焦点放在Input组件上。 如何做到这一点?

我已经尝试过裁判,但我无法做到这一点:

<FormControl
    onClick={this.textInput.focus()}
    style={{ display: 'block', cursor: 'text' }}
>
<Input
  error={this.props.error}
  disabled={this.props.disabled}
  ref={(input) => { this.textInput = input; }}
/>
</FormControl>

我对material-ui不太熟悉,但是我认为这里有两个问题。 首先,您对onClick值不是一个函数,因此在实例化该组件时,它将在尚未定义的ref上调用focus 您可以通过包装以下调用来解决此问题: () => this.textInput.focus() (或为其创建方法/实例属性。)

其次, material-uiInput组件包装在withStyles高阶组件中,当您使用ref ,它引用包装的组件,该组件没有focus方法。 相反,您可以使用inputRef ,该inputRef创建对实际input DOM元素的引用。 (请参阅https://material-ui-next.com/customization/api/#internal-components

此代码应工作:

..
  <FormControl
    onClick={() => this.textInput.focus()}
    style={{ display: 'block', cursor: 'text' }}
  >
    <Input
      error={this.props.error}
      disabled={this.props.disabled}
      inputRef={(input) => { this.textInput = input; }}
    />
  </FormControl>
..

问题可能出在上下文以及FormControl元素中处理click事件的方式。

尝试以下方法:

constructor(props) {
  super(props);
  this.setFocus = this.setFocus.bind(this);
}
setFocus() {
  this.textInput.focus();
}
render() {
  return(
    <FormControl
      onClick={this.setFocus}
      style={{ display: 'block', cursor: 'text' }}
    >
      <Input
        error={this.props.error}
        disabled={this.props.disabled}
        ref={(input) => { this.textInput = input; }}
      />
    </FormControl>
  );
}

作为注释,请记住,如果您使用某种动画,则可能是在安装主要组件时尚未创建输入。 在这种情况下, setTimeout的计时器要比动画时间长。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM