react怎么指定ref的三种方式
原创字符串方法
class Demo entends React.Component{
const {input1} = this.refs
showData = () => {
console.log(input1.value)
}
render(){
return(
)
}
}
备注 :这种方法虽然简单,但存在效率问题,已被废弃。
回调函数模式
class Demo entends React.Component{
const {input2} = this // 注意此处与字符串方法的区别,没有refs
showData2 = () => {
console.log(input2.value)
}
render(){
return(
this.input2 = c} />
)
}
}
备注 :如果ref回调函数基于 内联函数
以以下方式定义 更新过程
它被执行两次,即第一次传入参数时。 null
,然后是第二个传入参数。DOM元素。这是因为每次呈现时都会创建一个新的函数实例,因此。React清空旧的ref并设置新的。通过 将ref定义了回调函数class绑定方法
问题是可以避免的,但在大多数情况下,这些问题是无关紧要的。
class绑定方式:
class Demo entends React.Component{
const {input2} = this // 注意此处与字符串方法的区别
saveInput = (c) => { // class回调函数的形式
this.input2 = c
}
showData2 = () => {
console.log(input2.value)
}
render(){
return(
// 指定class回调函数的形式
)
}
}
createRef方式
class Demo entends React.Component{
// React.createRef可以在调用后返回容器。
// 该容器可以被储存。ref已标识的节点,货柜是“专用”的,一一对应。
myRef = React.createRef()
showData3 = () => {
console.log(this.myRef.current.value)
// 不要忘记.current.value
}
render(){
return(
)
}
}
备注 :是最复杂的文字,也是react最受推荐的方式
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除
上一篇:怎么理解React中受控组件和非受控组件 下一篇:redux的纯函数和高阶函数区别