这篇文章主要介绍了react中ref获取dom或者组件的实现方法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
react中ref获取dom或者组件方法
使用ref获取DOM的引用
在vue中,如果想获取DOM元素时,可以使用this.$refs.引用名称
在react中也可以像vue中,有类似的写法,如下
为元素添加ref引用
<h2 ref="test">这是h2标签</h2>
在页面上获取元素
this.refs.test
使用ref获取组件的引用
为组件添加ref引用
<Text ref="hellow"/>
在页面上使用组件的引用
this.refs.hellow
注意点: 只要使用ref拿到组件的引用对象,它就是组件的实例对象,因此就可以调用这个组件的方法,或者它的属性
react中的三种ref获取DOM节点
第一种 ref字符串方式获取Dom节点方式
已废弃的原始方法
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'))
第二种 回调式获取Dom节点方式
开发常用
class Dom extends React.Component{
showInputDom = () =>{
const {userNameInput} = this
console.log(userNameInput);
}
render(){
return (
<div>
{/*注释 (currentNode)=>{this.userNameInput =currentNode} 这里边的currentNode 为 当前的node节点 简称c *
织梦狗教程
本文标题为:react中ref获取dom或者组件的实现方法


基础教程推荐
猜你喜欢
- 解决:layUI数据表格+简单查询 2022-12-16
- Ajax提交表单并接收json实例代码 2023-02-13
- JavaScript垃圾回收机制(引用计数,标记清除,性能优 2022-08-31
- 在IE中为abbr标签加样式 2022-10-16
- ajax实现数据分页查询 2023-01-31
- AJax 把拿到的后台数据在页面中渲染的实例 2023-02-22
- Unicode中的常用字母小结 2022-09-21
- 原生ajax瀑布流demo分享(必看篇) 2023-02-01
- 纯javascript的ajax实现php异步提交表单的简单实例 2022-12-28
- 关于ajax异步访问数据的问题 2023-02-23