一、如何理解refs
组件标签可以通过ref来定义自己的标识,与原生js中的标签id相似
渲染组件到页面的时候给组件标签添加ref属性,就可以在this.refs.xxx来获得组件的真实DOM
二、ref的几种定义形式
字符串形式的ref(后续版本不是很支持了)
//创建组件
class Demo extends React.Component{
//展示左侧输入框的数据
showData = ()=>{
const {input1} = this.refs
alert(input1.value)
}
//展示右侧输入框的数据
showData2 = ()=>{
const {input2} = this.refs
alert(input2.value)
}
render(){
return(
<div>
<input ref="input1" type="text" placeholder="点击按钮提示数据"/>
<button onClick={this.showData}>点我提示左侧的数据</button>
<input ref="input2" onBlur={this.showData2} type="text" placeholder="失去焦点提示数据"/>
</div>
)
}
}
//渲染组件到页面
ReactDOM.render(<Demo a="1" b="2"/>,document.getElementById('test'))
回调函数形式的ref
就是在组件标签中的ref属性写成函数的样子,并且这个函数接收的参数是当前组件的DOM节点,在这个函数里面具体要做的事情就是,把当前的DOM节点绑定在组件实例上
//创建组件
class Demo extends React.Component{
//点击弹出数据回调
clickShowDate = ()=>{
const input1 = this.input1
alert(input1.value)
}
//失去焦点弹出数据回调
onBlurShowDate = ()=>{
const input2 = this.input2
alert(input2.value)
}
render(){
return(
//注意返回时只能有一个跟标签
<div>
<input ref={(currentNode)=>{this.input1 = currentNode}} type="text" placeholder="点击按钮提示数据"/>
<button onClick={this.clickShowDate}>点击获得数据</button>
<input ref={(currentNode)=>{this.input2 = currentNode}} onBlur={this.onBlurShowDate} type="text" placeholder="失去焦点提示数据"/>
</div>
)
}
}
//渲染组件到页面
ReactDOM.render(<Demo a="1" b="2"/>,document.getElementById('test'))
关于回调函数形式的ref会被调用几次
如果ref回调函数是以内联函数的方式定义的,在更新过程中(也就是执行多次render)他会被执行两次,第一次传入的参数是null,然后第二次会传入参数DOM元素。这是因为在每次渲染时会创建一个新的函数实例,所以React清空旧的ref并且设置新的。通过将ref的回调函数定义成class的绑定函数的方式可以避免上述问题,但是大多数情况他是无关紧要的
三、createRef()形式的ref
React.createRef调用后可以返回一个容器,该容器可以存储被ref所标识的节点,该容器是“专人专用”的
//创建组件
class Demo extends React.Component{
/*
React.createRef调用后可以返回一个容器,该容器可以存储被ref所标识的节点,该容器是“专人专用”的
*/
myRef = React.createRef()
myRef2 = React.createRef()
//展示左侧输入框的数据
showData = ()=>{
alert(this.myRef.current.value);
}
//展示右侧输入框的数据
showData2 = ()=>{
alert(this.myRef2.current.value);
}
render(){
return(
<div>
<input ref={this.myRef} type="text" placeholder="点击按钮提示数据"/>
<button onClick={this.showData}>点我提示左侧的数据</button>
<input onBlur={this.showData2} ref={this.myRef2} type="text" placeholder="失去焦点提示数据"/>
</div>
)
}
}
//渲染组件到页面
ReactDOM.render(<Demo a="1" b="2"/>,document.getElementById('test'))
注意:尽量避免过度使用ref,什么条件能避免?发生时间的元素是我们需要的ref元素就可以避免,因为react是采用事件委托的方式进行事件绑定的,只需要用event.target就能拿到目标元素和ref结果一致
react的事件处理
(1).通过onXxx属性指定事件处理函数(注意大小写)
a.React使用的是自定义(合成)事件, 而不是使用的原生DOM事件 —————— 为了更好的兼容性
b.React中的事件是通过事件委托方式处理的(委托给组件最外层的元素) ————————为了的高效
(2).通过event.target得到发生事件的DOM元素对象 ——————————不要过度使用ref