0

我在反应中实现表单输入验证时遇到了问题。一旦我打开表单,总是有 [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>
     );

}
4

1 回答 1

1

您将输入的值设置为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 } }))`.
于 2021-03-15T18:52:26.943 回答