2015-08-14 27 views
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名以上的字段。我使用兩個函數來更新狀態,而不是如何使用單個函數來更新狀態對象?是否還有其他最佳實踐?

+1

檢查這個http://stackoverflow.com/questions/21029999/react-js-identifying-different-inputs-with-one-onchange-handler – knowbody

+1

@knowbody由於它是有用的 –

+0

也作爲一個側面說明你可以編寫你的函數,例如:'onChangeRank(ext){}'[more here](https://github.com/lukehoban/es6features#classes) – knowbody

回答

0

解決此問題的最常見模式是使用bind()來爲onchange回調注入值。這是@knowbody引用的(React.js: Identifying different inputs with one onChange handler

另一種類似的模式是在元素中添加第二個標記以標識要更改的狀態屬性的名稱。我將用你的代碼展示一個使用label的例子(顯然你想使用專用標籤,因爲label用於顯示並且將被本地化)。

onInputChanged(evt) { 
    var newState = this.state, 
     propName = evt.target.label.toLowerCase(); 

    newState[propName] = evt.target.value; 
    this.setState(newState); 
};