【问题标题】:this.textInput.focus is not a function - Reactthis.textInput.focus 不是一个函数 - React
【发布时间】:2020-05-11 18:47:44
【问题描述】:

我有用于密码输入的 FormControl,带有切换掩码的图标,所以你看不到你正在输入的字符。但每当我切换此蒙版时,我也想重新聚焦输入字段。

<FormGroup
    className="input-text input-text--password"
    controlId={id}
    validationState={submitFailed && touched && error ? 'error' : validationState}
  >

    <FormControl
      {...input}
      disabled={disabled}
      className="input-text__input"
      autoFocus={autoFocus}
      type={maskEnabled ? 'password' : 'input'}
      onChange={this.handleFormControlChange}
      maxLength={maxLength}
      ref = { ref => this.textInput = ref }
    />
    <div
        className={'input-text__button ' + (maskEnabled ? 'mask-enabled' : 'mask-disabled')}
        onClick={this.handleToggleInputMode}
    />

...我用这个方法对焦:

handleToggleInputMode() {
  let newMaskEnabled = !this.state.maskEnabled;
  this.setState({maskEnabled: newMaskEnabled});
  this.textInput.focus();
}

但我不断收到错误

未捕获的 TypeError:this.textInput.focus 不是函数

所以我尝试将其放入 ComponentDidMount 但随后整个组件停止响应(不接受我输入的任何字符)。 我错过了什么?

【问题讨论】:

标签: javascript jquery reactjs


【解决方案1】:

请查看工作演示

 class App extends React.Component {
  componentDidMount() {
    this.textInput.focus();
  }
  render() {
    return (
      <div>
        <div>
          <input
            defaultValue="It will not focus"
          />
        </div>
        <div>
          <input
            ref={(input) => { this.textInput = input; }}
            defaultValue="with focus"
          />
        </div>
      </div>
    );
  }
}
    
ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.js"></script>
<div id="app"></div>

编辑

对于 FormControl,您应该按照 documentation 使用 inputRef

<FormControl inputRef={ref => { this.input = ref; }} />

【讨论】:

  • 我做了,但没有帮助。我认为这两种语法是等价的。
  • 我做到了,我认为不同之处在于我使用了对 ref 有不同支持的 formControl。如果你想找到它,你必须使用 findDOMNode。我最终使用 inputRef 而不是普通的 ref 解决了这个问题
  • 很高兴听到您解决问题,如果您愿意,可以添加您的答案
  • inputRef 为我做了。
  • 你能看看这个类似的问题stackoverflow.com/questions/63766100/…吗?
【解决方案2】:

根据当前文档 (https://reactjs.org/docs/refs-and-the-dom.html),使用:

this.textInput.current.focus();

所以它应该引用current来获取DOM节点。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-02
  • 2017-06-25
  • 2018-10-19
  • 2016-07-31
  • 2018-09-22
  • 2021-07-18
  • 2021-01-26
相关资源
最近更新 更多