reactjs 当useEffect钩子触发时,React Ref未定义

iqjalb3h  于 2023-11-18  发布在  React
关注(0)|答案(1)|浏览(88)

我写了一个组件,我想在组件加载时将focus字段聚焦。在useEffect中,我必须使用setTimeout,否则我会得到一个错误“Cannot read properties of null(阅读'focus')”,因为在useEffect钩子触发时引用没有加载。
有人知道为什么会这样吗?

import {useEffect, useRef} from 'react';
import {Modal, Button, TextInput, Label} from 'flowbite-react';
import {Head, useForm} from '@inertiajs/react';

export default function Register() {
    const {data, setData, post, processing, errors, reset} = useForm({
        username: '',
        email: '',
        password: '',
    });

    const usernameInputRef = useRef(null);

    useEffect(() => {
        setTimeout((() =>{
            usernameInputRef.current.focus()
        }), 100)


        return () => {
            reset('password');
        };
    }, []);


    const submit = (e) => {
        e.preventDefault();
        post(route('register'));
    };

    return (
        <>
            <Head title="Register Now"/>
            <Modal show="true">
                <form className="overflow-scroll" onSubmit={submit}>
                    <Modal.Header>Sign Up</Modal.Header>
                    <Modal.Body>

                        <div>
                            <Label htmlFor="username" value="Username"/>

                            <TextInput
                                id="username"
                                name="username"
                                value={data.username}
                                className="mt-1 block w-full"
                                autoComplete="username"
                                onChange={(e) => setData('username', e.target.value)}
                                required
                                color={errors.username ? "failure" : ""}
                                helperText={
                                    <>
                                        <span className="font-medium">{errors.username}</span>
                                    </>
                                }
                                ref={usernameInputRef}
                            />
                        </div>

                        <div className="mt-4">
                            <Label htmlFor="email" value="Email"/>

                            <TextInput
                                id="email"
                                type="text"
                                name="email"
                                value={data.email}
                                className="mt-1 block w-full"
                                autoComplete="username"
                                onChange={(e) => setData('email', e.target.value)}
                                required
                                color={errors.email ? "failure" : ""}
                                helperText={
                                    <>
                                        <span className="font-medium">{errors.email}</span>
                                    </>
                                }
                            />

                        </div>

                        <div className="mt-4">
                            <Label htmlFor="password" value="Password"/>

                            <TextInput
                                id="password"
                                type="password"
                                name="password"
                                value={data.password}
                                className="mt-1 block w-full"
                                autoComplete="new-password"
                                onChange={(e) => setData('password', e.target.value)}
                                required
                                color={errors.password ? "failure" : ""}
                                helperText={
                                    <>
                                        <span className="font-medium">{errors.password}</span>
                                    </>
                                }
                            />
                        </div>
                    </Modal.Body>
                    <Modal.Footer>
                        <div className="flex items-center justify-end  w-full">
                            <Button type="submit" className="w-full text-center" disabled={processing}>Register</Button>
                        </div>
                    </Modal.Footer>
                </form>
            </Modal>
        </>
    );
}

字符串

a1o7rhls

a1o7rhls1#

我认为你应该检查usernameInputRef.current试试这个:

useEffect(() => {
      setTimeout(() => {
        if (usernameInputRef.current) {
          usernameInputRef.current.focus();
        }
      }, 100);
      return () => {
        reset('password');
      };
    }, []);

字符串

useEffect(() => {
      setTimeout(() => {
        if (usernameInputRef.current) {
          usernameInputRef.current.focus();
        }
      }, 100);
    
      return () => {
        reset('password');
      };
    }, [usernameInputRef]);

相关问题