0

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

该项目似乎是用更旧版本的 React 编写的,所以我不得不尝试更新它——这就是我目前所拥有的:

应用程序.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;

活动.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 的背景,所以这种方法总体上我觉得很不寻常!

4

2 回答 2

0

将此绑定到nextStep函数:

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

或者在构造函数中:

constructor(props){
    super(props);
    this.nextSteps = this.nextSteps.bind(this);
}
于 2016-11-09T05:09:52.740 回答
0

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

<button onClick={()=>this.nextStep()}>Save &amp; Continue</button>
于 2016-11-09T02:22:45.547 回答