React表单自动聚焦的实现
发布时间:2022-10-31 23:17:34 332 相关标签: # javascript# 前端# react.js# java# java
有时候,为了进一步提升用户体验,我们需要在组件render之后,就自动聚焦到表单的input输入框,用户直接输入内容。
现在有这样的表单:

函数组件
import React from "react";
function Form() {
const [inputValue, setInputValue] = React.useState("")
const ele = React.useRef(null);
const handleInputChange = ({ target: { value } }) => {
setInputValue(value)
}
React.useEffect(() => {
ele.current.focus();
}, [])
return <div>
<form>
<p>Input:<input type="text" ref={ele} value={inputValue} onChange={handleInputChange} /></p>
<p><button>提交</button></p>
</form>
</div>
}
export default Form;
函数组件是在useEffect函数内处理初始化操作的,如果UI部分是用了Antd的话,用法也是一样的:
import React from 'react';
import 'antd/dist/antd.css';
import './index.css';
import { Button, Checkbox, Form, Input } from 'antd';
const App = () => {
const onFinish = (values) => {
console.log('Success:', values);
};
const onFinishFailed = (errorInfo) => {
console.log('Failed:', errorInfo);
};
const inputRef = React.useRef(null);
React.useEffect(()=>{
inputRef.current.focus()
},[])
return (
<Form
name="basic"
labelCol={{
span: 8,
}}
wrapperCol={{
span: 16,
}}
initialValues={{
remember: true,
}}
onFinish={onFinish}
onFinishFailed={onFinishFailed}
autoComplete="off"
>
<Form.Item
label="Username"
name="username"
rules={[
{
required: true,
message: 'Please input your username!',
},
]}
>
<Input ref={inputRef} />
</Form.Item>
<Form.Item
label="Password"
name="password"
rules={[
{
required: true,
message: 'Please input your password!',
},
]}
>
<Input.Password />
</Form.Item>
<Form.Item
name="remember"
valuePropName="checked"
wrapperCol={{
offset: 8,
span: 16,
}}
>
<Checkbox>Remember me</Checkbox>
</Form.Item>
<Form.Item
wrapperCol={{
offset: 8,
span: 16,
}}
>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
);
};
效果图:

class组件
import React from "react";
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
inputValue: ''
}
}
handleInputChange = (event) => {
this.setState({
inputValue: event.target.value
})
}
componentDidMount() {
this.element.focus();
}
render() {
const { inputValue } = this.state;
return <div>
<form>
<p>Input:<input type="text" ref={(element) => { this.element = element }} value={inputValue} onChange={this.handleInputChange} /></p>
<p><button>提交</button></p>
</form>
</div>
}
}
效果图:

在input的ref属性上定义一个回调函数,这个回调函数是在组件挂载阶段被调用,参数element,表示是输入的DOM实列。组件卸载阶段也是调用这个组件,通过传入null来释放内存。
文章来源: https://blog.51cto.com/u_12344418/5802213
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报