react如何让输入框聚焦
使用 ref 和 useRef 钩子
在 React 中,可以通过 useRef 钩子创建一个 ref 对象,并将其绑定到输入框的 ref 属性上。通过调用 ref 对象的 current.focus() 方法,可以让输入框获得焦点。
import React, { useRef, useEffect } from 'react';
function FocusInput() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
}, []);
return <input ref={inputRef} type="text" />;
}
在类组件中使用 createRef
如果是类组件,可以使用 React.createRef() 创建 ref,并在 componentDidMount 生命周期方法中调用 focus()。
import React from 'react';
class FocusInput extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
componentDidMount() {
this.inputRef.current.focus();
}
render() {
return <input ref={this.inputRef} type="text" />;
}
}
通过事件触发聚焦
可以通过按钮点击或其他事件触发输入框的聚焦。将 ref 绑定到输入框,并在事件处理函数中调用 focus()。
import React, { useRef } from 'react';
function FocusInput() {
const inputRef = useRef(null);
const handleClick = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={handleClick}>Focus Input</button>
</div>
);
}
自动聚焦表单中的下一个输入框
在表单中,可以通过监听 onKeyDown 事件,在按下回车键时自动聚焦到下一个输入框。
import React, { useRef } from 'react';
function FormWithAutoFocus() {
const input1Ref = useRef(null);
const input2Ref = useRef(null);
const handleKeyDown = (e, nextRef) => {
if (e.key === 'Enter') {
nextRef.current.focus();
}
};
return (
<div>
<input
ref={input1Ref}
type="text"
onKeyDown={(e) => handleKeyDown(e, input2Ref)}
/>
<input ref={input2Ref} type="text" />
</div>
);
}
使用 forwardRef 传递 ref
如果需要将 ref 传递给自定义组件,可以使用 React.forwardRef 包装组件,确保 ref 能够正确传递到内部的输入框。
import React, { forwardRef, useRef, useEffect } from 'react';
const CustomInput = forwardRef((props, ref) => {
return <input ref={ref} type="text" {...props} />;
});
function FocusInput() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
}, []);
return <CustomInput ref={inputRef} />;
}






