【问题标题】:React - Focus on input using nameReact - 使用名称专注于输入
【发布时间】:2017-01-02 19:51:16
【问题描述】:

我有一个带输入的组件,有什么方法可以使用名称来集中注意力吗?

<div onClick={this.handleClick.bind(this)}>
    ... Some more code ...
        <input type="text" name={this.props.name} onChange={this.props.onChange} autoFocus/>
    ... Some more code ...
</div>

点击父 div 时,我附加了一个点击事件。

handleClick(e) {
    // Need to focus may be using refs, but not sure how to do it.
    return this.props.onClick(this.props.name);
}

【问题讨论】:

  • 您应该能够使用输入 autoFocus 属性进行自动对焦。但是如果你有多个文本框并且在加载过程中都需要关注最后一个会赢

标签: javascript reactjs input react-redux


【解决方案1】:

组件:

<div onClick={this.handleClick.bind(this)}>
    ... Some more code ...
        <input type="text" ref={(input) => { this.input = input; }} name={this.props.name} onChange={this.props.onChange} autoFocus/>
    ... Some more code ...
</div>

点击处理程序:

handleClick(e) {
    this.input.focus();
    return this.props.onClick(this.props.name);
}

或

组件:

<div onClick={this.handleClick.bind(this)}>
    ... Some more code ...
        <input type="text" ref={this.props.name} name={this.props.name} onChange={this.props.onChange} autoFocus/>
    ... Some more code ...
</div>

点击处理程序:

handleClick(e) {
    this.refs[this.props.name].focus();
    return this.props.onClick(this.props.name);
}

【讨论】:

  • 我认为在第二种方法中,这将引用 div 而不是输入。都试过了,但没有运气。
  • 您是否收到一些错误消息?您是否尝试在 componentDidMount 内添加带有 this.refs 的日志以检查是否定义了 refs?
  • 我没有看到任何错误,我不确定如何在componenetDidMount 中记录this,refs 这是否适用于测试? componentDidMount(){ console.log(this.props.name); }
  • 我看到裁判没有被渲染&lt;input type="text" name="pets" placeholder="NO INFO FOUND" data-reactid=".0.2.0.5.0.1.$0.0.1.1"&gt;
  • ref 是虚拟 DOM 的一个属性,它不会出现在“真实”DOM 上。
猜你喜欢
  • 2022-10-16
  • 1970-01-01
  • 2019-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多