2
我是新來的無功功能。我正在使用ES6開發react + flux + alt。 我有一個用於創建新記錄的表單。如何通過調用onChange函數將值推入狀態 - 反應
元器件
import React from 'react';
import { Input, Button, Glyphicon, ButtonToolbar } from 'react-bootstrap';
import AttributeSectionStore from 'stores/attributeSection/AttributeSectionStore';
import TextBoxesSet from '../descriptionTextBoxes';
import styles from 'scss/_common';
export default class AttributeSection extends React.Component {
constructor(props) {
super(props);
}
_onCreate =() => {
console.log('___________', this.state);
}
onChangeName = (evt) => {
this.setState({name: evt.target.value});
};
onChangeRank = (evt) => {
this.setState({rank: evt.target.value});
};
static getPropsFromStores() {
return recordStore.getState();
}
render() {
return (
<div className="container">
<div className={styles.mainheader}>
<h2 >New Record</h2>
</div>
<div className="col-md-9">
<form className="form-horizontal">
<div className="row">
<div className="col-md-12">
<Input type="text" label="Name" labelClassName="col-xs-2"
wrapperClassName="col-xs-4" value={this.props.name}
onChange={this.onChangeName}/>
</div>
</div>
<div className="row">
<div className="col-md-12">
<Input type="number" label="Rank" labelClassName="col-xs-2"
wrapperClassName="col-xs-4" value={this.props.rank}
onChange={this.onChangeRank}/>
</div>
</div>
<div className="row">
<div className="col-md-4 col-md-offset-2">
<ButtonToolbar className={styles.formBtnGrp}>
<Button bsStyle="primary" onClick={this._onCreate}>Create</Button>
<Button type="reset">Cancel</Button>
</ButtonToolbar>
</div>
</div>
</form>
</div>
</div>
);
}
}
AttributeSection.propTypes = {
name: React.PropTypes.string
rank: React.PropTypes.number
};
使用上述組件現在我發現了數據轉換成狀態,但形式可以有2名以上的字段。我使用兩個函數來更新狀態,而不是如何使用單個函數來更新狀態對象?是否還有其他最佳實踐?
檢查這個http://stackoverflow.com/questions/21029999/react-js-identifying-different-inputs-with-one-onchange-handler – knowbody
@knowbody由於它是有用的 –
也作爲一個側面說明你可以編寫你的函數,例如:'onChangeRank(ext){}'[more here](https://github.com/lukehoban/es6features#classes) – knowbody