「这是我参与2022首次更文挑战的第3天,活动详情查看:2022首次更文挑战」
组件实例核心三大属性之refs
string类型的ref
这个拿到组件的用法相当于getElementById('input1')
<script type="text/babel" >
class Demo extends React.Component{
Demo =()=>{
const {input1} =this.refs
alert(input1.value)
}
Lose =()=>{
const {input2} =this.refs
}
render(){
return (
<div>
<input placeholder ="点击按钮出发事件" ref="input1"/>
<button onClick = {this.Demo}>确定</button>
<input placeholder ="失去焦点触发事件" onBlur={this.Lose} ref ="input2"/>
</div>
)
}
}
ReactDOM.render(<Demo/>,document.getElementById('test'))
</script>
回调函数形式的ref
react官方不推荐使用string类型的ref,因为写多了有效率问题,并且后面的版本有可能移除
<script type="text/babel" >
class Demo extends React.Component{
Demo =()=>{
const {input1} = this
alert(input1.value)
}
Lose =()=>{
const {input2} =this.refs
}
render(){
return (
<div>
//回调函数形式的ref
<input placeholder ="点击按钮出发事件" ref={c => {this.input1 = c}}/>
<button onClick = {this.Demo}>确定</button>
<input placeholder ="失去焦点触发事件" onBlur={this.Lose} ref ="input2"/>
</div>
)
}
}
ReactDOM.render(<Demo/>,document.getElementById('test'))
</script>
回调ref回调次数的问题
zh-hans.reactjs.org/docs/refs-a…
createRef(容器的方式创建)
<script type="text/babel" >
class Demo extends React.Component{
//1.使用createRef的方式创建,相当于创建了一个容器(专人专用)
myRef = React.createRef()
myRef2 = React.createRef()
Demo =()=>{
alert(this.myRef.current.value)
}
Lose =()=>{
const {input2} =this.refs
alert(this.myRef2.current.value)
}
render(){
return (
<div>
<input placeholder ="点击按钮出发事件" ref={this.myRef}/>
<button onClick = {this.Demo}>确定</button>
<input placeholder ="失去焦点触发事件" onBlur={this.Lose} ref ={this.myRef2}/>
</div>
)
}
}
ReactDOM.render(<Demo/>,document.getElementById('test'))
</script>
发生事件的元素正好是需要操作的元素可以省略ref
(1).通过OnXxx属性指定事件处理函数(注意大小写)
a.React使用的是自定义(合成)事件,而不是使用原生的DOM事件——为了更好的兼容性
b.React中的事件是通过事件委托方式处理的(委托给组件最外层的元素) ——为了更加高效
比如这边要记录点击每个li的操作,实际上对外层的ul记录就可以
<ul>
<li></li>
<li></li>
<li></li>
</ul>
(2).通过event.target得到发生事件的DOM元素对象 ——不要过度使用ref
\