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

新手上路,请多包涵

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

  1. 有一个标签,里面有一些内容
  2. 如果单击,文本输入将其替换为可用标签的内容
  3. 用户可以编辑内容
  4. 按下回车后,输入隐藏,标签返回更新内容

我终于可以完全正确(实际上是使用 MongoBD 后端、redux 等),而我唯一不能做的事情(花一整天时间在谷歌搜索和阅读 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 来进一步获得价值of,每个组件,我无法想象如果我的 ref 没有命名,我怎么能得到这个值!

所以你能给出一个想法,帮助我理解,如果我不使用表单(因为我需要一个输入框替换标签),当它的 CSS(引导)类丢失时,我如何设置它的焦点’隐藏’好吗?

原文由 Ariam1 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 456
2 个回答

您使用 refs 的方式不是最首选的方式,否则它不再是最佳实践。尝试这样的事情

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>
    );
  }
}

更新

React 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>
    );
  }
}

原文由 TRomesh 发布,翻译遵循 CC BY-SA 4.0 许可协议

只需将 自动对焦 属性添加到 input 。 ( 当然在 JSX 它是 autoFocus

 <input autoFocus ...

原文由 Mehdi Dehghani 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进