在React中更新表单状态的正确方法
Correct way to update form states in React?
所以我有一个去在我的第一个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 & 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 & Continue</button>
将这个绑定到nextStep函数:
<button onClick={this.nextStep.bind(this)}>Save & Continue</button>
或者在构造函数中:
constructor(props){
super(props);
this.nextSteps = this.nextSteps.bind(this);
}
相关文章:
- Angular:如何在状态更改时调用scope方法
- 返回当前状态名称的方法
- 经典方法的目的|与对象状态的关系
- 检查 redux 状态是否更改的简单方法
- 无法更新componentWillReceiveProps方法内的状态
- 在状态更改后调用方法
- 如何使用jquery cookie插件保存toggleClass方法的状态
- 管理形式状态的最简单方法是什么
- 在 redux 化简器中更新状态的正确方法
- HTTP 状态 405 - 不支持请求方法“POST”(Spring MVC)
- 在Redux中更新嵌套状态的更干净/更短的方法
- 尽管成功传输了 json,但我的 Jquery.ajax 方法在响应中获得了错误状态
- Ember 应用程序就绪状态 - 应用程序无法识别方法
- 从状态提供程序的解析方法更改角度应用程序的状态
- 使用 javascript 实现状态检查的最佳方法
- 在 html5 上检查在线状态的最佳方法
- 在 Angular.js 中更改视图时处理$scope状态和值的正确方法是什么?
- 控制台状态方法不可用,但似乎应该可用
- 使用无状态功能组件与调用方法有什么区别
- 方法POST,状态(已取消)错误消息