工作中不免遇到各种react版本,获取dom元素/值是常见需求。但是因为各种升级或兼容的各种问题,日常工作中会遇到不同的react版本。所以今天针对目前的几个重要版本点提供不同的解决方案。欢迎留言讨论补充。感谢 ^ _ ^
针对多个react版本 - 父组件获取子组件的dom元素/值
React 16.3版本以上
第一、获取当前组件的dom,使用createRef实现
import React, {
Component, createRef} from 'react';
class Example extends Component {
constructor(){
super();
this.inputRef = createRef();
}
handleClick = () => {
alert(this.inputRef.current.value);
}
render(){
return(
<>
<input type='text' ref={
this.inputRef}/><br/>
<button onClick={
this.handleClick}>get input value</button>
</>
);
}
}
export default Example;
注意点
- 通过current属性访问Dom
- React 会在组件挂载时给 current 属性传入 DOM 元素,并在组件卸载时传入 null 值。ref 会在 componentDidMount 或 componentDidUpdate 生命周期钩子触发前更新。
- ref属性绑到组件上可以调用组件内的方法。但仅限于class声明的。你不能在函数组件上使用 ref 属性,因为它们没有实例。
第二、获取公用组件的dom,使用forwardRef实现
公用组件 - 写法一
import React from 'react';
const Input = React.forwardRef((props, ref)=>(
<input ref={
ref} {
...props}/>
));
export default Input