Left forwarding is a technique for automatically passing a ref through a component to one of its children.
在上一篇的博客中,介绍了当点击按钮时,对应的输入框就会出现光标,现在就用别的方法来实现这个功能
// FRInput.js 文件
import React from 'react'
const FRInput = React.forwardRef((props, ref) => {
return (
<div>
<input type="text" ref={ref} />
</div>
)
})
export default FRInput
// FRParentInput.js 文件
import React, { Component } from 'react'
import FRInput from './FRInput'
class FRParentInput extends Component {
constructor(props) {
super(props)
this.inputRef = React.createRef()
}
clickHandler = () => {
this.inputRef.current.focus()
}
render() {
return (
<div>
<FRInput ref={this.inputRef}/>
<button onClick={this.clickHandler}>Focus Input</button>
</div>
)
}
}
export default FRParentInput
// App.js 文件
import React from 'react';
import './App.css';
import FRParentInput from './FRParentInput'
function App() {
return (
<div className="App">
<FRParentInput/>
</div>
);
}
export default App;
结果如下:
初始结果是这样的
当点击按钮Focus Input时,输入框就会变成这样:
如果觉得不错的话,就用点赞来代替五星好评吧!