【问题标题】:Set focus on input - React Component将焦点放在输入上 - React 组件
【发布时间】:2023-06-13 00:29:01
【问题描述】:

我有一个反应组件,它有一个带有禁用属性的输入字段。单击组件后,输入将启用,用户可以在该字段上键入。我能够做到这一点,但我需要专注于启用输入字段。

Attributes.js

basicAmenitiesList.map(function(item, index){
     return <Attribute key={index} 
                       name={item.amenity_id} 
                       type={item.title} 
                       icon={item.icon} 
                       selected={item.isSelected} 
                       value={item.value} 
                       onClick={_this.handleClick.bind(this)} 
                       onChange={_this.handleChange.bind(this)}/>
})

属性文件:

<div onClick={this.handleClick.bind(this)}>
...
       <input type="text" name={this.props.name}
              ref={this.props.name}
              placeholder="NO INFO FOUND"
              value={this.props.value}
              disabled={!this.props.selected}
              onChange={this.props.onChange}
       />
</div>

handleClick(e) {
    // I need to focus on enabling., that is when **this.props.selected** is true.
    return this.props.onClick(this.props.name);
}

更新

我尝试使用 onFocus 进行输入,

onFocus(){
    this.refs.pets.focus();
}

现在我将 refs 名称硬编码为 pets,但是有没有办法通过发送带有 onFocus 的名称来使其动态化?

【问题讨论】:

    标签: javascript reactjs input redux react-redux


    【解决方案1】:

    您可以使用 autoFocus 作为输入属性

    <input type="text" name={this.props.name}
                  ref={this.props.name}
                  placeholder="NO INFO FOUND"
                  value={this.props.value}
                  disabled={!this.props.selected}
                  onChange={this.props.onChange}
                  autoFocus
           />
    

    【讨论】:

    • 我有同样的问题,不幸的是,自动对焦属性在我的情况下不是一个选项(可能是多个嵌套/隐藏输入)
    最近更新 更多