【问题标题】:Cannot read property 'firstname' of null in Reactjs无法在 Reactjs 中读取 null 的属性“名字”
【发布时间】:2025-12-13 10:35:02
【问题描述】:

我正在尝试使用反应钩子 useState 从表单中获取数据。但是我在获取输入字段的值时遇到了错误Cannot read property 'firstname' of null。以下是我的注册和挂钩文件。 registration.js

import React from 'react';
import {
    Container, Col, Form,
    FormGroup, Label, Input,
    Button,
} from 'reactstrap';
import useRegistrationForm from './hooks';


const Registration = () => {
    const register = () => {
        alert(`User Created!
               Name: ${inputs.firstName} ${inputs.lastName}
               Email: ${inputs.email}`);
    }
    const { inputs, handleInputChange, handleSubmit } = useRegistrationForm(register);

    return (
        <div>
            <Container className="container">
                <h2>Registration</h2>
                <Form onSubmit={handleSubmit} className="form">
                    <Col>
                        <FormGroup>
                            <Label className="label"> First Name</Label>
                            <Input type="text" name="firstname" id="examplename" placeholder="Enter First Name"
                                onChange={handleInputChange} value={inputs.firstname}required></Input>
                        </FormGroup>
                    </Col>
                 
                    <Button>Submit</Button>
                </Form>
            </Container>
        </div>
    )
}
export default Registration

【问题讨论】:

  • 我想我们需要看看import useRegistrationForm from './hooks'的代码
  • 在您的register 函数中,您指的是inputs 变量,该变量不一定存在于您调用该函数的范围内。

标签: javascript reactjs


【解决方案1】:

在警报中,您正在使用inputs.firstName。 会不会是这个原因?
而不是firstname >> firstName

【讨论】:

    最近更新 更多