小编典典

如何以编程方式反应焦点输入

reactjs

我正在尝试实现一个非常简单的用例,UI功能,其中:

  1. 有一个带有一些内容的标签
  2. 如果单击,则将文本输入替换为可用标签的内容
  3. 用户可以编辑内容
  4. 按下回车键时,输入将隐藏并且标签将返回具有更新内容的内容

我最终可以完全正确(实际上是使用MongoBD后端,redux等),而我唯一做不到的事情(花了一整天的时间在Google上搜索和阅读SOF类似的帖子)是:

当我的文字输入出现时,我无法将焦点转移到它上!首先我这样累了:

<div className={((this.state.toggleWordEdit) ? '' : 'hidden')}>
<input id={this.props.word._id} className="form-control"
        ref="updateTheWord" 
        defaultValue={this.state.word}
        onChange={this.handleChange}
        onKeyPress={this.handleSubmit}
        autoFocus={this.state.toggleWordEdit}/></div>
    <div className={((this.state.toggleWordEdit) ? 'hidden' : '')}>
      <h3 onClick={this.updateWord}>
        {this.state.word}</h3>
    </div>

但是autoFocus肯定无法正常工作(我“猜测”是因为呈现了表单,但是处于隐藏状态,这使autoFocus毫无用处)。

接下来,我在this.updateWor中尝试了很多在Google和SOF上找到的建议:

this.refs.updateTheWord.focus();

与类似的建议一起都无效。我也试图愚弄React,只是看我是否能做点什么!我使用了真正的DOM:

    const x = document.getElementById(this.props.word._id);
    x.focus();

而且也不起作用。我什至无法理解的一件事是这样的建议:
使用ref作为方法(我“猜”),
我什至没有尝试,因为我有多个这些成分,我需要ref才能进一步获得价值。 ,每个组件,我无法想象如果我的引用没有命名,如何获得价值!

所以,请您提出一个想法,以帮助我了解如果我不使用Form(因为我需要一个输入框来替换标签),当CSS(Bootstrap)类丢失“隐藏吗?


阅读 236

收藏
2020-07-22

共1个答案

小编典典

您使用裁判的方式已不再是首选,也不是最佳实践。尝试这样的事情

class MyClass extends React.Component {
  constructor(props) {
    super(props);
    this.focus = this.focus.bind(this);
  }

  focus() {
    this.textInput.current.focus();
  }

  render() {

    return (
      <div>
        <input
          type="text"
          ref={(input) => { this.textInput = input; }} />
        <input
          type="button"
          value="Set Focus"
          onClick={this.focus}
        />
      </div>
    );
  }
}

更新
阵营16.3 向上您可以使用 React.createRef() API

class MyClass extends React.Component {
  constructor(props) {
    super(props);
    // create a ref to store the textInput DOM element
    this.textInput = React.createRef();
    this.focus = this.focus.bind(this);
  }

  focus() {
    // Explicitly focus the text input using the raw DOM API
    // Note: we're accessing "current" to get the DOM node
    this.textInput.current.focus();
  }

  render() {
    // tell React that we want to associate the <input> ref
    // with the `textInput` that we created in the constructor
    return (
      <div>
        <input
          type="text"
          ref={this.textInput} />
        <input
          type="button"
          value="Set Focus"
          onClick={this.focus}
        />
      </div>
    );
  }
}
2020-07-22