首页 > 解决方案 > 使用 ref 更改字段的焦点

问题描述

我试图改变对按钮点击的关注,但没有任何反应。我从官方反应文档中工作。我的代码段是:

我在构造函数中定义了 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>

标签: reactjsref

解决方案


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

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

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

这应该有效。


推荐阅读