【问题标题】:Change focus of fields with ref使用 ref 更改字段的焦点
【发布时间】:2020-11-03 13:58:24
【问题描述】:

我正在尝试将焦点更改为单击按钮,但没有任何反应。我从官方反应文档中工作。我的 sn-p 代码是:

我在构造函数中定义了 ref

 constructor(props) {
    super(props)
    this.firstInput = React.createRef()
 }

然后写一个函数来设置焦点

    changeFocus = () => {
       this.firstInput.current.focus()
    }

然后定义一个按钮在点击时调用函数

  <Button onClick={this.changeFocus}>
    Focus
  </Button>

最后在组件中设置 ref

<Col className="pr-md-1" md="3">
  <FormGroup>
    <label>Broj računa</label>
    <Input style={{'borderColor':'lightgray', 'fontSize':'14px'}}
           ref={this.firstInput}
           placeholder="Br.računa"
           type="text"
           value={this.state.accountNumber || (header === null ? "" : header.account_number) }
           onChange={this.changeAccountNumber}
    />
   </FormGroup>
  </Col>

【问题讨论】:

  • 显示Input实现,你需要它来传递ref到html元素。
  • 您很可能没有将 ref 转发到 Input 组件。正如@DennisVash 提到的,您确实需要向我们展示Input 组件的实现...

标签: reactjs ref


【解决方案1】:

我猜你正在使用reactstrap(需要innerRef而不是ref)所以你需要进行以下更改

innerRef={(input) => { this.firstInput = input }}

   changeFocus = () => {
       this.firstInput.focus()
    }

这应该可行。

【讨论】:

  • 是的! tnx,这正是我需要的。我正在使用 reactstrap,问题出在 ref 中,我需要使用 innerRef。 tnx 很多
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-14
  • 2017-04-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多