本篇文章和大家了解一下react中ref获取dom或者组件如何实现。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。
在vue中,如果想获取DOM元素时,可以使用this.$refs.引用名称
在react中也可以像vue中,有类似的写法,如下
为元素添加ref引用
<h3 ref="test">这是h3标签</h3>
在页面上获取元素
this.refs.test
为组件添加ref引用
<Text ref="hellow"/>
在页面上使用组件的引用
this.refs.hellow
注意点: 只要使用ref拿到组件的引用对象,它就是组件的实例对象,因此就可以调用这个组件的方法,或者它的属性
已废弃的原始方法
class Dom extends React.Component{
showInputDom = () =>{
const {userNameInput} = this.refs
console.log(userNameInput);
}
render(){
return (
<div>
<input ref="userNameInput" type="text"/>
<button onClick={this.showInputDom}>点击显示inpuDom</button>
</div>
)
}
}
ReactDOM.render(<Dom/>,document.getElementById('root'))
开发常用
class Dom extends React.Component{
showInputDom = () =>{
const {userNameInput} = this
console.log(userNameInput);
}
render(){
return (
<div>
{/*注释 (currentNode)=>{this.userNameInput =currentNode} 这里边的currentNode 为 当前的node节点 简称c */}
{/*<input ref={(currentNode)=>{this.userNameInput =currentNode}} type="text"/>*/}
<input ref={(c)=>{this.userNameInput = c}} type="text"/>
<button onClick={this.showInputDom}>点击显示inpuDom</button>
</div>
)
}
}
ReactDOM.render(<Dom/>,document.getElementById('root'))
class Dom extends React.Component{
// 挂载到了自身实例上了
userNameInput= (c) =>{
this.input1 = c ;
console.log(c);
}
render(){
return (
<div>
{/*会在试图更新时调用两次 第一次赋值为null,第二次赋值为dom节点*/}
{/*<input ref={(c)=>{this.userNameInput =c}} type="text"/>*/}
{/*在试图更新时不会调用}
{/*<input ref={ this.userNameInput } type="text"/>*/}
{/*注意这俩个方法是有区别的,这两个对项目的影响可以忽略不记*/}
<input ref={this.userNameInput} type="text"/>
<button onClick={this.showInputDom}>点击显示inpuDom</button>
</div>
)
}
}
ReactDOM.render(<Dom/>,document.getElementById('root'))
以上就是react中ref获取dom或者组件如何实现的简略介绍,当然详细使用上面的不同还得要大家自己使用过才领会。如果想了解更多,欢迎关注亿速云行业资讯频道哦!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://blog.csdn.net/zsm4623/article/details/86593832