如何在反应中实现表单输入验证

How to implement form input validation in the react

我在 React 中实现表单输入验证时遇到了问题。 打开表单后,总会有 [object object] 作为默认输入出现。 这是显示:

理想情况下,我希望显示如下:

这是我的代码,知道我该如何修复它吗?

const ErrorValidationLabel = ({ txtLbl }) => (
    <label htmlFor="" style={{ color: "red" }}>
        {txtLbl}
    </label>
);
const txtFieldState = {
    value: "",
    valid:true,
}
class Setting extends Component {
    constructor() {
        this.state = {
            name: {...txtFieldState, fileName:"name", required:true, requiredTxt:"Device ID is required"} ,
    }
    this.handleNameChange = this.handleNameChange.bind(this);
    this.handleNameSearch = this.handleNameSearch.bind(this);
    handleNameChange(event) {
        this.setState({ name: event.target.value });
    }
    handleNameSearch(event) {
        //http request call logic
    }
}
 render() {
        const renderNameError = this.state.name.valid? "" : <ErrorValidationLabel txtLbl={this.state.name.requiredTxt} />;
     return (
        <form onSubmit={this.handleNameSearch}>
                                <label >
                                    Enter Your Device Id:
                            </label>
                                <Input  name="name" type="text" placeholder="ex:12345678910" value={this.state.name} onChange={this.handleNameChange} required/>
                                {renderNameError}
                                <Input type="submit"  value="Search Device" />
                            </form>
     );

}

您正在将输入值设置为 this.state.name,但 this.state.name 是一个对象。

        this.state = {
            name: {...txtFieldState, fileName:"name", required:true, requiredTxt:"Device ID is required"}
        }

您应该将其设置为 this.state.name.value

不过,我应该警告您,代码 this.setState({ name: event.target.value }) 将覆盖您的整个 name 对象,这可能不是您想要的。

您已经在使用展开运算符,所以我建议

this.setState(state => ({ name: { ...state.name, value: event.target.value } }))`.