何时使用 Refs
下面是几个适合使用 refs 的情况:
- 管理焦点,文本选择或媒体播放。
- 触发强制动画。
- 集成第三方 DOM 库。
ref的三种使用方法
- 字符串(官网不推荐使用)
- 回调ref
class Demo extends React.Component{
render () {
return (
<div>
<input type="text" ref={el =>{ this.input1 = el}}></input>
<button onClick={this.show}>点我显示数据</button>
<input type="text" onBlur={this.show2} ref={ el => this.input2 = el}></input>
</div>
)
}
show = () => {
const { input1} = this
alert(input1.value)
}
show2 = () => {
const { input2} = this
alert(input2.value)
}
}
复制代码
- React.createRef()创建
- 当 ref 属性用于 HTML 元素时,构造函数中使用 React.createRef() 创建的 ref 接收底层 DOM 元素作为其 current 属性。
- 当 ref 属性用于自定义 class 组件时,ref 对象接收组件的挂载实例作为其 current 属性。
- 不能在函数组件上使用 ref 属性。
class Test extends React.Component{
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render () {
return (
<div>
<input type="text" onBlur={this.show} ref={ this.myRef }></input>
</div>
)
}
show = () => {
const { myRef} = this
alert(myRef.current.value)
}
}
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END