推广 热搜: 二手  净利2626万  北京  二手车  SMM废铜现货交易日评  企业  全国  汽车  三星  公司 

react中ref获得dom或者组件怎么样达成

   日期:2024-11-06     来源:www.8kwenku.com    作者:二手网    浏览:467    评论:0    
核心提示:[db:简介]
react中ref获得dom或者组件办法用ref获得DOM的引用

在vue中,假如想获得DOM元素时,可以用this.$refs.引用名字

在react中也可以像vue中,有类似的写法,如下

为元素添加ref引用

h3ref=test这是h3标签/h3

在页面上获得元素

this.refs.test用ref获得组件的引用

为组件添加ref引用

Textref=hellow/

在页面上用组件的引用

this.refs.hellow

注意点: 只须用ref拿到组件的引用对象,它就是组件的实例对象,因此就能调用这个组件的办法,或者它的属性

react中的三种ref获得DOM节点第一种 ref字符串方法获得Dom节点方法

已废弃的原始办法

classDomextendsReact.Component{showInputDom=()={const{userNameInput}=this.refsconsole.log(userNameInput);}render(){return(divinputref=userNameInputtype=text/buttononClick={this.showInputDom}点击显示inpuDom/button/div)}}ReactDOM.render(Dom/,document.getElementById(root))第二种 回调式获得Dom节点方法

开发常用

classDomextendsReact.Component{showInputDom=()={const{userNameInput}=thisconsole.log(userNameInput);}render(){return(div{}{}inputref={(c)={this.userNameInput=c}}type=text/buttononClick={this.showInputDom}点击显示inpuDom/button/div)}}ReactDOM.render(Dom/,document.getElementById(root))第三种 回调式获得Dom节点方法 挂在到自己实例

classDomextendsReact.Component{//挂载到了自己实例上了userNameInput=(c)={this.input1=c;console.log(c);}render(){return(div{}{}{}{}inputref={this.userNameInput}type=text/buttononClick={this.showInputDom}点击显示inpuDom/button/div)}}ReactDOM.render(Dom/,document.getElementById(root))

 
标签: react
打赏
 
更多>同类二手资讯
0相关评论

热门推荐
推荐图文
推荐二手资讯
点击排行
网站首页  |  关于我们  |  联系方式  |  免责声明  |  版权隐私  |  网站地图  |  排名推广  |  广告服务  |  积分换礼  |  网站留言  |  RSS订阅  |  违规举报