简体   繁体   中英

Correct way to update form states in React?

So I'm having a go at my first React app using create-react-app , and I'm trying to make a multi-stage form based on this GitHub project. In particular the AccountFields and Registration parts.

That project seems to have been written in a much older version of React, so I've had to try and update it - and this is what I have so far:

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;

I've looked at a number of examples, and this seems to be the right approach to store the current state (to allow users to go back and forth between different parts of the form), and to then store the values from this stage. When I click the Save & Continue button, I get an error saying Cannot read property 'props' of null . I mean obviously this means this is null, but I'm unsure of how to fix it.

Am I approaching this the wrong way? Every example I find seems to have a completely different implementation. I come from an Apache-based background, so this approach in general I find very unusual!

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

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

Bind this to nextStep function:

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

Or in the constructor:

constructor(props){
    super(props);
    this.nextSteps = this.nextSteps.bind(this);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM