芜湖中凡网站建设公司,国网商城,网站建设 app开发网站,公司网站要更新1、字符串形式 这种字符出串写法因为效率不好#xff0c;所以不推荐使用 语法 标签上使用refname 进行绑定 方法中this.refs.name拿到dom
input refinput1 typetext placeholder点击按钮弹出内容 /
button onC…1、字符串形式 这种字符出串写法因为效率不好所以不推荐使用 语法 标签上使用refname 进行绑定 方法中this.refs.name拿到dom
input refinput1 typetext placeholder点击按钮弹出内容 /
button onClick{ this.showData }按钮/button
showData () {const { input1 } this.refsalert(input1.value)
}2、回调的形式 ref会自动执行回调函数并注入一个参数currentNode当前节点 更新组件时refs会执行两次第一次传null第二次传入参数dom元素并不会影响正常开发 原因是每次渲染时都会定义一个新的函数实例所以React清空旧的ref并且设置新的。 通过将ref的回调函数定义成class的绑定函数方式可以避免这个问题 语法 标签上使用ref{cthis.namec} 方法中this.name拿到dom
//正常写法
input ref{c this.input1 c } typetext placeholder点击按钮弹出内容 /
button onClick{ this.showData }按钮/button
showData () {const { input1 } thisalert(input1.value)
}//解决执行两次的问题
input ref{this.demo} typetext placeholderclass绑定的函数 /
demo(c) {console.log(c,123123)
}3、使用React.createRef React.createRef调用后返回一个容器该容器可以存储被ref所标识的节点该容器只能给单个使用重复的容器会被覆盖 语法 标签上使用ref{this.name} 给实例添加属性input React.createRef(); input ref{this.input} typetext placeholder点击按钮弹出内容 /button onClick{ this.showData }按钮/buttonshowData () {alert(this.input.current.value)}