今天爱分享给大家带来react 中的 ref 的如何使用【方法总结】,希望能够帮助到大家。
方式1:string类型绑定
类似于vue中的ref绑定方式,可以通过this.refs.绑定的ref的名字获取到节点dom
import React from 'react'
class CommentForm extends React.Component
{
constructor(){
super();
this.addComment = this.addComment.bind(this);
}
addComment(e){
var user = this.refs.user.value;
var content = this.refs.content.value;
}
render()
{
return (
)
}
}
export {CommentForm as default}
注意:的是 这种方式已经不被最新版的react推荐使用,使用会报错
index.js:1 Warning: A string ref, “user”, has been found within a strict mode tree. String refs are a source of potential bugs and should be avoided. We recommend using useRef() or createRef() instead.
方法2:react.CreateRef()
通过在class中使用React.createRef()方法创建一些变量,可以将这些变量绑定到标签的ref中
那么该变量的current则指向绑定的标签dom
import React from 'react'
class CommentForm extends React.Component
{
constructor(){
super();
this.addComment = this.addComment.bind(this);
}
user = React.createRef();
content = React.createRef();
addComment(e){
var user = this.user.current.value;
var content = this.content.current.value;
}
render()
{
return (
)
}
}
export {CommentForm as default}
方法3:函数形式
在class中声明函数,在函数中绑定ref
使用这种方法可以将子组件暴露给父组件以使得父组件能够调用子组件的方法
import React from 'react'
class CommentForm extends React.Component
{
constructor(){
super();
this.addComment = this.addComment.bind(this);
}
user = null;
content = null;
fnUser = el => this.user = el;
fnContent = el => this.content = el;
addComment(e){
var user = this.user.value;
var content = this.content.value;
console.log(user);
console.log(content);
}
render()
{
return (
)
}
}
export {CommentForm as default}
注意:
react并不推荐过度使用ref,如果能通过state做到的事情,就不应该使用 refs 在你的 app 中“让事情发生”。过度使用ref并不符合数据驱动的思想

![熟女游戏v0.65 AI版[PC+安卓/11.5G/更新]MILF Games [v0.65] [欧美SLG/汉化/动态]](/wp-content/uploads/replace/2025/10/11/ed8d23b71055dd9439d6c5665abba2b7.webp)