【发布时间】:2018-04-27 09:46:02
【问题描述】:
我是 React 新手 :)。我创建了一个非常简单的 React 控件,称为 CustomInput,但是当单击按钮时,onChange 处理程序会启动,但是当它的最终值在处理程序中是可以的但它没有在表单上更新(或被覆盖) )。
问题出在哪里?
我的 CustomInput 代码如下:
"use strict";
var React = require('react');
var CustomInput = React.createClass({
propTypes: {
value: React.PropTypes.string.isRequired,
name: React.PropTypes.string.isRequired
/*
error: React.PropTypes.string
label: React.PropTypes.string.isRequired,
onChange: React.PropTypes.func.isRequired,
placeholder: React.PropTypes.string,
value: React.PropTypes.string,
*/
},
getInitialState: function() {
debugger;
return {
value: '',
errors: {},
dirty: false
};
},
onChange: function(event) {
debugger;
var value = event.target.value + "%";
this.state.value = value;
console.log("onChange: "+this.state.value);
return this.setState({value: this.state.value});
},
render: function () {
var wrapperClass = 'form-group';
if (this.props.error && this.props.error.length > 0) {
wrapperClass += " " + 'has-error';
}
var textStyle = { "text-align": "center" };
return (
<div className={wrapperClass}>
<label htmlFor={this.props.name}>{this.props.label}</label>
<div className="field">
<input type="text"
name={this.props.name}
className="form-control"
placeholder="enter value"
ref={this.props.name}
value={this.props.value}
onChange={this.onChange}
style={textStyle}
/>
<div className="input">{this.props.error}</div>
</div>
</div>
);
}
});
module.exports = CustomInput;
更新 1: 我的包含 CustomInput 控件的组件如下所示:
"use strict";
var React = require('react');
var peopleApi = require('../../../api/peopleApi');
var CustomInput = require('../common/customInput');
//var PeopleList = require('./peopleList');
var AuthorPage = React.createClass({
getInitialState: function() {
//debugger;
return {
person: {}
};
},
componentDidMount: function() {
if (this.isMounted()) {
//debugger;
this.setState({person: peopleApi.getPersonById(this.props.personId)});
}
},
render: function() {
return (
<div>
<h1>Person</h1>
<CustomInput value={this.state.person.id} name="personId" error = "" label= "ID"/>
<CustomInput value={this.state.person.name} name="personName" error="" label= "Name"/>
<CustomInput value={this.state.person.salary} name="personSalary" error="" label="Pensja"/>
<CustomInput value={this.state.person.spelnieniePercent} name="personSpelnienie" error="" label= "Spelnienie [%]"/>
<CustomInput value={this.state.person.dataUrodzenia} name="personDataUrodzenia" error="" label="Data urodzenia:"/>
</div>
);
}
});
module.exports = AuthorPage;
更新 2:更新函数 onChange() 后:
onChange: function(event) {
debugger;
var value = event.target.value + "%";
//this.state.value = value;
//console.log("onChange: "+this.state.value);
return this.setState({ value }, () => console.log("onChange: ", this.state.value));
},
但还是一样的效果:新值被原值覆盖。
【问题讨论】:
标签: reactjs