reactjs - 使用 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>
解决方案
我猜你正在使用reactstrap
(需要innerRef
而不是ref
)所以你需要进行以下更改
innerRef={(input) => { this.firstInput = input }}
和
changeFocus = () => {
this.firstInput.focus()
}
这应该有效。
推荐阅读
- python - 编写代码以在许多文本文件中搜索某些单词
- python - API 请求 - 存储 JSON - 稍后分析
- javascript - 将分页添加到 wordpress 帖子列表
- macos - 如何从 Mac 中正确删除 node_modules?
- javascript - 如何使用 Nerdamer.js 获得正确的解决方案
- python - Mysql Python Connector 由于目标机器主动拒绝,无法连接
- python - 如何使用 Python 将单个数据插入到 Mysql 表中?
- delphi - 通过样式更改 firemonkey 网格的选择字体颜色
- typescript - 作为函数的参数传递的通用箭头函数的指示返回类型无效
- c++ - .clang-format 函数参数连续对齐