javascript - React Form 文本框不会在击键之间保留数据

标签 javascript reactjs

我在这里做错了什么?在我开始连接状态之前,下面的表格工作正常。如果我断点或记录代码,我可以看到 'this.state.data.xxx' 的值在事件方法调用时被更改,但数据随后立即从文本框中清空并且不会保留。我只能认为我在某处做错了什么。

export default class RegistrationForm extends React.Component {

    constructor(props) {
        super(props);
        this.state = { 
            data: {},
            employersLookupData: []
        };

        this.employersDataSource = new LookupRestServiceGateway("/api/lookups/employers/");

        this.handleEmailChange = this.handleEmailChange.bind(this);
        this.handlePasswordChange = this.handlePasswordChange.bind(this);
        this.handleConfirmPasswordChange = this.handleConfirmPasswordChange.bind(this);
        this.handleFirstNameChange = this.handleFirstNameChange.bind(this);
        this.handleLastNameChange = this.handleLastNameChange.bind(this);
        this.handleEmployerChange = this.handleEmployerChange.bind(this);
    }

    handleEmailChange(e) {
        console.log(this);
        this.state.data.email = e.target.value;
    }

    handlePasswordChange(e) {
        this.state.data.password = e.target.value;
    }

    handleConfirmPasswordChange(e) {
        this.state.data.confirmPassword = e.target.value;
    }

    handleFirstNameChange(e) {
        this.state.data.firstName = e.target.value;
    }

    handleLastNameChange(e) {
        this.state.data.lastName = e.target.value;
    }

    handleEmployerChange(e) {
        this.state.data.employerID = e.target.value;
    }

    loadLookupData() {
        this.employersDataSource.getListItems({ successCallback: (data) => {
            this.setState({ employersLookupData: data ? data.items : [] });
        }});
    }

    componentDidMount() {
        this.loadLookupData();
    }

    render() {                                                                  
        return (
            <Form.Wrapper formId = "registration-form"
                          className = "form-horizontal"
                          onSubmit = {this.onSubmit}
                          onSubmitSuccess = {this.onSubmitSuccess}>
                <h4>Create a new account.</h4>
                <hr/>
                <Form.Line name = "Email" 
                           label = "Email" 
                           type = "email"
                           inputClassName = "col-md-10 col-sm-9" labelClassName = "col-md-2 col-sm-3"
                           value = {this.state.data.email || ""}
                           onChange = {this.handleEmailChange} />
                <Form.Line name = "Password" 
                           label = "Password" 
                           type = "password"
                           inputClassName = "col-md-10 col-sm-9" labelClassName = "col-md-2 col-sm-3"
                           value = {this.state.data.password || ""}
                           onChange = {this.handlePasswordChange} />
                <Form.Line name = "ConfirmPassword" 
                           label = "Confirm Password" 
                           type = "password"
                           inputClassName = "col-md-10 col-sm-9" labelClassName = "col-md-2 col-sm-3"
                           value = {this.state.data.confirmPassword || ""}
                           onChange = {this.handleConfirmPasswordChange} />
                <Form.Line name = "FirstName" 
                           label = "First Name" 
                           inputClassName = "col-md-10 col-sm-9" labelClassName = "col-md-2 col-sm-3"
                           value = {this.state.data.firstName || ""}
                           onChange = {this.handleFirstNameChange} />
                <Form.Line name = "LastName" 
                           label = "Last Name" 
                           inputClassName = "col-md-10 col-sm-9" labelClassName = "col-md-2 col-sm-3"
                           value = {this.state.data.lastName || ""}
                           onChange = {this.handleLastNameChange} />
                <Form.DropDownLine name = "EmployerID"
                                   label = "Employer"
                                   inputClassName = "col-md-10 col-sm-9" labelClassName = "col-md-2 col-sm-3"
                                   emptySelection = "Please select an employer&hellip;"
                                   onChange = {this.handleEmployerChange}
                                   items = {this.state.data.employersLookupData}/>                                    
                <Form.Buttons.Wrapper className="col-sm-offset-3 col-md-offset-2 col-md-10 col-sm-9">
                    <Form.Buttons.Submit text = "Register"
                                         icon = "fa-user-plus" />
                </Form.Buttons.Wrapper>     
            </Form.Wrapper>                                                                                                                  
        );
    }
}

为了完整起见,Form.Line 指的是下面的 FormLine 组件......

export default class FormLine extends React.Component {

    render() {
        let controlClassName = this.props.children 
            ? `form-control ${this.props.controlClassName} noted-form-control`
            : `form-control ${this.props.controlClassName}`;

        return (
            <div className="row padded-row">
                <div className="form-group">
                    <FormLabel name = {this.props.name} 
                               className = {this.props.labelClassName} 
                               value = {this.props.label} />
                    <div className={this.props.inputClassName}>
                        <TextBox name = {this.props.name} 
                                 className = {controlClassName} 
                                 maxLength = {this.props.maxLength} 
                                 value = {this.props.value} 
                                 type = {this.props.type} 
                                 onChange = {this.props.onChange} />
                        <FormInputNotes>{this.props.children}</FormInputNotes>
                    </div>
                </div>
            </div>
        );
    }
}

TextBox 看起来像这样......

export default function TextBox({name = "", value = "", type = "text", className = "", maxLength = 10000, onChange}) {
    return (
        <input type = {type}
               htmlFor = {name} 
               className = {`form-control ${className}`} 
               maxLength = {maxLength} 
               value = {value} 
               onChange = {onChange} />
    );
}

最佳答案

我认为你的问题是你误解了状态应该改变的方式。你正在这样做:

this.state.data.employerID = e.target.value;

你应该这样做:

let newData = {
  ...this.state.data,
  employerID: e.target.value
}
this.setState({data: newData});

举个例子:

让我们开始这样的初始状态:

this.state = { someValue: 0 };

执行 this.state.someValue = 1 不会通知 React 状态已经改变,所以它永远不会渲染 canges。 这里是 this.setState 发生的地方,使用它会通知 React Core 状态已经改变并且需要重新计算(并在之后渲染)。跟随示例的正确方法是:

this.setState({ someValue: 0 });

在你的例子中,由于你使用的是一个复杂的对象,你需要替换完整的对象,这就是为什么你需要制作一个副本,更改你需要的值并使用 this.setState.

您的处理程序应该大致如下所示:

handleFirstNameChange(e) {
  //Create a copy of the original object
  let newData = {
    ...this.state.data,
    //Set the new value
    employerID: e.target.value
  }
  //Set the new value through setState
  this.setState({data: newData});
}

有关 React 组件的引用或更多信息,请阅读 the full docs .如果您有时间,也可以看看组件循环生命周期。

让我知道它是否有效。

关于javascript - React Form 文本框不会在击键之间保留数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42929256/

相关文章:

javascript - 如何从url中获取参数?

javascript - RxJS 在 Ajax 错误后继续监听

javascript - sigma.js 中的自定义行为

javascript - 为什么这个弹出窗口打开时是空白的?

reactjs - React native init 错误找不到模块-> node_modules\react-native\package.json'

reactjs - 如何在我的 React 组件中使用 SCSS 变量

javascript - 我应该在我的 UI 组件库中的什么地方包含 React 作为依赖项?

javascript - 正则表达式 : How to replace the matched text with a HTML element in JavaScript?

javascript - Console.log显示隐藏对象信息

reactjs - React 生命周期方法的类型安全