react中ref如何触发
在React中使用ref触发操作
React中的ref用于直接访问DOM节点或React组件实例。通过ref可以触发DOM操作或调用子组件方法。
创建ref的三种方式
字符串ref(已废弃)
<input ref="myInput" />
// 通过this.refs.myInput访问
回调ref
<input ref={(el) => this.inputRef = el} />
// 通过this.inputRef访问
createRef API
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <input ref={this.myRef} />;
}
// 通过this.myRef.current访问
使用ref触发DOM操作
聚焦输入框
componentDidMount() {
this.inputRef.current.focus();
}
获取DOM属性
const height = this.myRef.current.clientHeight;
触发动画
this.myRef.current.style.transform = 'translateX(100px)';
在函数组件中使用useRef
基本用法
import { useRef } from 'react';
function MyComponent() {
const inputRef = useRef(null);
const handleClick = () => {
inputRef.current.focus();
};
return (
<>
<input ref={inputRef} />
<button onClick={handleClick}>Focus Input</button>
</>
);
}
转发ref到子组件
使用forwardRef允许父组件访问子组件的DOM节点
const ChildComponent = React.forwardRef((props, ref) => (
<button ref={ref}>{props.children}</button>
));
function ParentComponent() {
const buttonRef = useRef(null);
useEffect(() => {
buttonRef.current.focus();
}, []);
return <ChildComponent ref={buttonRef}>Click me</ChildComponent>;
}
注意事项
ref不应过度使用,优先考虑React的数据流和状态管理。仅在需要直接操作DOM或调用组件方法时使用ref。避免在渲染期间访问ref,因为此时ref可能尚未设置。






