新网站seo,wordpress批量审核,搜狗站长工具,网站 建设 语言目录
React中提供两种方法创建ref对象#xff1a;
类组件获取 Ref 三种方式
① Ref属性是一个字符串。
② Ref 属性是一个函数。
③ Ref属性是一个ref对象。
高级用法1#xff1a;forwardRef 转发 Ref
高级用法2#xff1a;ref实现组件通信 【ref作用】#xff1a;最…
目录
React中提供两种方法创建ref对象
类组件获取 Ref 三种方式
① Ref属性是一个字符串。
② Ref 属性是一个函数。
③ Ref属性是一个ref对象。
高级用法1forwardRef 转发 Ref
高级用法2ref实现组件通信 【ref作用】最熟悉的就是 用 Ref 获取真实 DOM 元素和获取类组件实例除此之外的功能ref 派生出一些其他的高级用法能够解决一些特殊场景下的问题 React中提供两种方法创建ref对象 第一种 类组件中 React.createRef 创建一个 ref 对象。 class Index extends React.Component{constructor(props){super(props)this.currentDom React.createRef(null)}componentDidMount(){console.log(this.currentDom)}render () div ref{ this.currentDom } ref对象模式获取元素或组件/div
}第二种函数组件中 React.useRef 创建 Ref export default function Index(){const currentDom React.useRef(null)React.useEffect((){console.log( currentDom.current ) // div},[])return div ref{ currentDom } ref对象模式获取元素或组件/div
}【什么是 ref 对象所谓 ref 对象就是用 createRef 或者 useRef 创建出来的对象】 【问在函数组件中为什么不能用 createRef 】 答类组件有一个实例 instance 能够维护像 ref 这种信息但函数组件每次更新时所有的变量都会重新声明此时 ref 就会随着函数组件执行被重置。 类组件获取 Ref 三种方式 ① Ref属性是一个字符串。 /* 类组件 */
class Children extends Component{ render()divhello,world/div
}/* TODO: Ref属性是一个字符串 */
export default class Index extends React.Component{componentDidMount(){console.log(this.refs)}render() divdiv refcurrentDom 字符串模式获取元素或组件/divChildren refcurrentComInstance //div
}React 在底层逻辑会判断类型如果是 DOM 元素会把真实 DOM 绑定在组件 this.refs (组件实例下的 refs )属性上如果是类组件会把子组件的实例绑定在 this.refs 上。(函数组件没有实例不能被 Ref 标记) ② Ref 属性是一个函数。 class Children extends React.Component{ render()divhello,world/div
}/* TODO: Ref属性是一个函数 */
export default class Index extends React.Component{currentDom nullcurrentComponentInstance nullcomponentDidMount(){console.log(this.currentDom)console.log(this.currentComponentInstance)}render() divdiv ref{(node) this.currentDom node } Ref模式获取元素或组件/divChildren ref{(node) this.currentComponentInstance node } //div
}③ Ref属性是一个ref对象。 class Children extends React.Component{ render()divhello,world/div
}export default class Index extends React.Component{currentDom React.createRef(null)currentComponentInstance React.createRef(null)componentDidMount(){console.log(this.currentDom)console.log(this.currentComponentInstance)}render() divdiv ref{ this.currentDom } Ref对象模式获取元素或组件/divChildren ref{ this.currentComponentInstance } //div
}高级用法1forwardRef 转发 Ref 高级用法2ref实现组件通信