在React中更新表单状态的正确方法

Correct way to update form states in React?

本文关键字:方法 状态 表单 React 更新      更新时间:2023-09-26

所以我有一个去在我的第一个React应用程序使用create-react-app,我试图使基于这个GitHub项目的多阶段形式。特别是AccountFields和Registration部分。

这个项目似乎是用旧版本的React编写的,所以我不得不尝试更新它-这是我到目前为止所做的:

App.js:

import React, { Component } from 'react';
import './App.css';
import Activity from './Activity';
var stage1Values = {
    activity_name : "test"
};
class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            step: 1
        };
    };
    render() {
        switch (this.state) {
            case 1:
                return <Activity fieldValues={stage1Values} />;
        }
    };
    saveStage1Values(activity_name) {
        stage1Values.activity_name = activity_name;
    };
    nextStep() {
        this.setState({
          step : this.state.step + 1
        })
    };
}
export default App;

Activity.js:

import React, { Component } from 'react';
class Activity extends Component {
    render() {
        return (
            <div className="App">
                <div>
                    <label>Activity Name</label>
                    <input type="text" ref="activity_name" defaultValue={this.props.stage1Values} />
                    <button onClick={this.nextStep}>Save &amp; Continue</button>
                </div>
            </div>
        );
    };
    nextStep(event) {
        event.preventDefault();
        // Get values via this.refs
        this.props.saveStage1Values(this.refs.activity_name.getDOMNode().value);
        this.props.nextStep();
    }
}
export default Activity;

我看了一些例子,这似乎是正确的方法来存储当前状态(允许用户在表单的不同部分之间来回),然后存储从这个阶段的值。当我点击Save & Continue按钮,我得到一个错误,说Cannot read property 'props' of null。我的意思是,显然这意味着this是空的,但我不确定如何修复它。

我是不是走错路了?我找到的每个例子似乎都有完全不同的实现。我的背景是基于apache的,所以我觉得这种方法非常不寻常!

nextStep中的this不是指向Activity,只是这样做

<button onClick={()=>this.nextStep()}>Save &amp; Continue</button>

这个绑定到nextStep函数:

<button onClick={this.nextStep.bind(this)}>Save &amp; Continue</button>
或者在构造函数中:
constructor(props){
    super(props);
    this.nextSteps = this.nextSteps.bind(this);
}