【问题标题】:Correct way to update form states in React?在 React 中更新表单状态的正确方法?
【发布时间】:2016-11-09 01:56:42
【问题描述】:

所以我正在尝试使用create-react-app 开发我的第一个 React 应用程序,并且我正在尝试基于this GitHub 项目制作一个多阶段表单。特别是 AccountFieldsRegistration 部分。

那个项目似乎是用旧版本的 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 &amp; Continue 按钮时,我收到一条错误消息Cannot read property 'props' of null。我的意思很明显这意味着this 为空,但我不确定如何修复它。

我是不是以错误的方式处理这个问题?我发现的每个示例似乎都有完全不同的实现。我来自基于 Apache 的背景,所以总的来说我觉得这种方法很不寻常!

【问题讨论】:

标签: javascript forms reactjs react-native create-react-app


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    this绑定到nextStep函数:

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

    或者在构造函数中:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-14
      • 2020-11-11
      • 2022-01-10
      • 2016-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多