react16中ref的使用
生活随笔
收集整理的這篇文章主要介紹了
react16中ref的使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在 React16 新版本中,新引入了 React.createRef 與 React.forwardRef 兩個 API,有計劃移除老的 string ref,使 ref 的使用更加便捷與明確。如果你的應用已經升級到 React16.3+ 版本,那就放心大膽使用 React.createRef 吧,如果暫時沒有的話,建議使用 callback ref 來代替 string ref。
string ref 使用
class MyComponent extends React.Component {componentDidMount() {this.refs.myRef.focus();}render() {return <input ref="myRef" />;} }callback ref 使用
class MyComponent extends React.Component {componentDidMount() {this.myRef.focus();}render() {return <input ref={(ele) => {this.myRef = ele;}} />;} }React.createRef 使用
class MyComponent extends React.Component {constructor(props) {super(props);this.myRef = React.createRef();}componentDidMount() {this.myRef.current.focus();}render() {return <input ref={this.myRef} />;} }總結
以上是生活随笔為你收集整理的react16中ref的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 抄袭一些别人工作中的小技巧
- 下一篇: 司机版运满满(「司机招聘」)