react的refs如何取值
获取 React Refs 的值
在 React 中,refs 用于直接访问 DOM 元素或 React 组件实例。根据 React 版本和使用方式的不同,获取 refs 值的方法也有所区别。
函数组件中使用 useRef
import React, { useRef } from 'react';
function MyComponent() {
const inputRef = useRef(null);
const handleClick = () => {
console.log(inputRef.current.value); // 获取输入框的值
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={handleClick}>Get Value</button>
</div>
);
}
类组件中使用 createRef
import React, { Component } from 'react';
class MyComponent extends Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
handleClick = () => {
console.log(this.inputRef.current.value); // 获取输入框的值
};
render() {
return (
<div>
<input ref={this.inputRef} type="text" />
<button onClick={this.handleClick}>Get Value</button>
</div>
);
}
}
回调 Refs(适用于旧版 React)
class MyComponent extends Component {
handleClick = () => {
console.log(this.inputRef.value); // 获取输入框的值
};
render() {
return (
<div>
<input ref={el => (this.inputRef = el)} type="text" />
<button onClick={this.handleClick}>Get Value</button>
</div>
);
}
}
访问自定义组件的 Refs
如果 ref 被附加到自定义类组件,ref.current 将指向该组件的实例,可以调用其方法或访问其状态:
class CustomInput extends Component {
focus = () => {
this.inputRef.focus();
};
render() {
return <input ref={el => (this.inputRef = el)} />;
}
}
class Parent extends Component {
componentRef = React.createRef();
componentDidMount() {
this.componentRef.current.focus(); // 调用子组件方法
}
render() {
return <CustomInput ref={this.componentRef} />;
}
}
注意事项
- 函数组件默认不支持
ref,除非使用forwardRef转发。 - 避免过度使用
refs,优先考虑 React 的数据流(props 和 state)。 ref.current在组件挂载前为null,需在useEffect或componentDidMount中访问。
转发 Refs(forwardRef)
若需在函数组件中暴露内部 DOM 节点的 ref:
const FancyInput = React.forwardRef((props, ref) => (
<input ref={ref} className="fancy" />
));
function Parent() {
const inputRef = useRef();
useEffect(() => {
inputRef.current.focus();
}, []);
return <FancyInput ref={inputRef} />;
}






