一、ref属性
一句话总结:标识组件内部的元素
1、React提供的这个ref属性(不能在无状态组件上使用 ref 属性,因为它们没有实例)表示为对组件真正实例的引用其实就是ReactDOM.render()返回的组件实例
2、ReactDOM.render()渲染组件时返回的是组件实例;而渲染dom元素时,返回是具体的dom节点。
二、ref属性–使用
React的ref有3种用法:
- 字符串(官方不推荐使用) 最早的ref用法。使用this.refs.xxx来进行访问
- 回调函数(官方推荐)
- React.createRef() (React16.3新提供)
官方建议
勿过度使用 Refs在对逻辑进行处理的时候尽量优先考虑state
//字符串方式
// class MyCom extends React.Component{
// fun=()=>{
// console.log(this.refs.ele.value)
// }
// render(){
// return(
// <div>
// <input type="text" ref="ele" placehold="请输入"/>
// <button onClick={this.fun}>点我查看</button>
// </div>
// )
// }
// }
// 回调函数
// class MyCom extends React.Component{
// fun=()=>{
// console.log(this.comp)
// this.comp.style.backgroundColor="yellow"
// }
// render(){
// return(
// <div>
// { /*demop---当前元素*/}
// <p ref={(demop)=>{this.comp=demop}}>标签</p>
// <button onClick={this.fun}>点我查看</button>
// </div>
// )
// }
// }
// 3、createRef 16.3新增
class MyCom extends React.Component {
constructor(props) {
super(props)
this.myRef = React.createRef()
}
fun = () => {
console.log(this.myRef.current)
}
render() {
return (
<div>
{ /*demop---当前元素*/}
<p ref={this.myRef}>标签</p>
<button onClick={this.fun}>点我查看</button>
</div>
)
}
}
ReactDOM.render(<MyCom />, document.getElementById("box"))
</script>