如何从material-ui TextField,DropDownMenu组件获取数据?

我创build表单,我有几个TextField,包括DropDownMenu材质的UI组件,问题是我如何从所有的TextFields,DropDownMenus在一个OBJ收集所有的数据,并将其发送到服务器上。 对于TextField,它有TextField.getValue()返回input的值。 但我不知道如何使用它。

var React = require('react'), mui = require('material-ui'), Paper = mui.Paper, Toolbar = mui.Toolbar, ToolbarGroup = mui.ToolbarGroup, DropDownMenu = mui.DropDownMenu, TextField = mui.TextField, FlatButton = mui.FlatButton, Snackbar = mui.Snackbar; var menuItemsIwant = [ { payload: '1', text: '[Select a finacial purpose]' }, { payload: '2', text: 'Every Night' }, { payload: '3', text: 'Weeknights' }, { payload: '4', text: 'Weekends' }, { payload: '5', text: 'Weekly' } ]; var menuItemsIcan = [ { payload: '1', text: '[Select an objective]' }, { payload: '2', text: 'Every Night' }, { payload: '3', text: 'Weeknights' }, { payload: '4', text: 'Weekends' }, { payload: '5', text: 'Weekly' } ]; var menuItemsHousing = [ { payload: '1', text: '[Select housing]' }, { payload: '2', text: 'Every Night' }, { payload: '3', text: 'Weeknights' }, { payload: '4', text: 'Weekends' }, { payload: '5', text: 'Weekly' } ]; var menuItemsIlive = [ { payload: '1', text: '[Select family mambers]' }, { payload: '2', text: 'Every Night' }, { payload: '3', text: 'Weeknights' }, { payload: '4', text: 'Weekends' }, { payload: '5', text: 'Weekly' } ]; var menuItemsLifestyle = [ { payload: '1', text: '[Select lifestyle]' }, { payload: '2', text: 'Every Night' }, { payload: '3', text: 'Weeknights' }, { payload: '4', text: 'Weekends' }, { payload: '5', text: 'Weekly' } ]; var menuItemsLifestyle2 = [ { payload: '1', text: '[Select savings]' }, { payload: '2', text: 'Every Night' }, { payload: '3', text: 'Weeknights' }, { payload: '4', text: 'Weekends' }, { payload: '5', text: 'Weekly' } ]; var menuItemsIncome = [ { payload: '1', text: '[Select your yearly income]' }, { payload: '2', text: 'Every Night' }, { payload: '3', text: 'Weeknights' }, { payload: '4', text: 'Weekends' }, { payload: '5', text: 'Weekly' } ]; var Content = React.createClass({ getInitialState: function() { return { //formData: { // name: '', // age: '', // city: '', // state: '' //}, errorTextName: '', errorTextAge: '', errorTextCity: '', errorTextState: '' }; }, render: function() { return ( <div className="container-fluid"> <div className="row color-bg"></div> <div className="row main-bg"> <div className="container"> <div className="mui-app-content-canvas page-with-nav"> <div className="page-with-nav-content"> <Paper zDepth={1}> <h2 className="title-h2">Now, what would you like to do?</h2> <Toolbar> <ToolbarGroup key={1} float="right"> <span>I want to</span> <DropDownMenu className="dropdown-long" menuItems={menuItemsIwant} //autoWidth={false} /> </ToolbarGroup> </Toolbar> <div className="clearfix"></div> <Toolbar> <ToolbarGroup key={2} float="right"> <span>So I can</span> <DropDownMenu className="dropdown-long" menuItems={menuItemsIcan} //autoWidth={false} /> </ToolbarGroup> </Toolbar> <h2 className="title-h2">Please, share a little about you.</h2> <div className="clearfix"></div> <Toolbar> <ToolbarGroup key={3} float="right"> <span>I am</span> <TextField id="name" className="text-field-long" ref="textfield" hintText="Full name" errorText={this.state.errorTextName} onChange={this._handleErrorInputChange} /> <span>and I am</span> <TextField id="age" className="text-field-short" ref="textfield" hintText="00" errorText={this.state.errorTextAge} onChange={this._handleErrorInputChange} /> <span className="span-right-measure">years of age.</span> </ToolbarGroup> </Toolbar> <div className="clearfix"></div> <Toolbar> <ToolbarGroup key={4} float="right"> <span>I</span> <DropDownMenu hintText="I" menuItems={menuItemsHousing} //autoWidth={false} /> <span>in</span> <TextField id="city" ref="textfield" className="text-field-long" hintText="City" errorText={this.state.errorTextCity} onChange={this._handleErrorInputChange} /> <span>,</span> <TextField id="state" ref="textfield" className="text-field-short text-field-right-measure" hintText="ST" errorText={this.state.errorTextState} onChange={this._handleErrorInputChange} /> </ToolbarGroup> </Toolbar> <div className="clearfix"></div> <Toolbar> <ToolbarGroup key={5} float="right"> <span>Where I live</span> <DropDownMenu className="dropdown-long" menuItems={menuItemsIlive} //autoWidth={false} /> </ToolbarGroup> </Toolbar> <div className="clearfix"></div> <Toolbar> <ToolbarGroup key={6} float="right"> <span>My lifestyle is</span> <DropDownMenu className="dropdown-short" menuItems={menuItemsLifestyle} //autoWidth={false} /> <span>and I've saved</span> <DropDownMenu className="dropdown-short" menuItems={menuItemsLifestyle2} //autoWidth={false} /> </ToolbarGroup> </Toolbar> <div className="clearfix"></div> <Toolbar> <ToolbarGroup key={7} float="right"> <span>My yearly household is about</span> <DropDownMenu className="dropdown-mobile" menuItems={menuItemsIncome} //autoWidth={false} /> </ToolbarGroup> </Toolbar> <div className="clearfix"></div> <div className="button-place"> <FlatButton onTouchTap={this._handleClick} label="I'm done lets go!" /> <Snackbar ref="snackbar" message="Invalid input, please check and try again" /> </div> </Paper> </div> </div> </div> </div> </div> ); }, _handleErrorInputChange: function(e) { if (e.target.id === 'name') { var name = e.target.value; this.setState({ //name: name, errorTextName: e.target.value ? '' : 'Please, type your Name' }); } else if (e.target.id === 'age') { var age = e.target.value; this.setState({ //age: age, errorTextAge: e.target.value ? '' : 'Check Age' }); } else if (e.target.id === 'city') { var city = e.target.value; this.setState({ //city: city, errorTextCity: e.target.value ? '' : 'Type City' }); } else if (e.target.id === 'state') { var state = e.target.value; this.setState({ //state: state, errorTextState: e.target.value ? '' : 'Type State' }); } }, _handleClick: function(e) { this.refs.snackbar.show(); //TODO: find a way to change errorText for all empty TextField if (this.refs.textfield && this.refs.textfield.getValue().length === 0) { this.setState({ errorTextState: 'Type State', errorTextCity: 'Type City', errorTextAge: 'Check Age', errorTextName: 'Please, type your Name' }); } } }); module.exports = Content; 

我想要在_handleClick方法在服务器上发送它。

为每个TextFieldDropDownMenu元素添加一个onChange处理函数。 调用它时,将这些input的新值保存在“ Content组件的state中。 在渲染中,从state检索这些值,并将它们作为value道具。 请参阅受控组件 。

 var Content = React.createClass({ getInitialState: function() { return { textFieldValue: '' }; }, _handleTextFieldChange: function(e) { this.setState({ textFieldValue: e.target.value }); }, render: function() { return ( <div> <TextField value={this.state.textFieldValue} onChange={this._handleTextFieldChange} /> </div> ) } }); 

现在,您在_handleClick方法中所要做的就是从this.state检索所有input的值,并将它们发送到服务器。

你也可以使用React.addons.LinkedStateMixinReact.addons.LinkedStateMixin这个过程。 请参阅双向绑定助手 。 以前的代码变成:

 var Content = React.createClass({ mixins: [React.addons.LinkedStateMixin], getInitialState: function() { return { textFieldValue: '' }; }, render: function() { return ( <div> <TextField valueLink={this.linkState('textFieldValue')} /> </div> ) } }); 

使用接受的答案/这是另一个(已经删除)问题的答案

@karopastal

给你的<TextField />组件添加一个ref属性,然后调用getValue(),如下所示:

零件:

 <TextField ref="myField" /> 

使用getValue:

 this.refs.myField.getValue() 

flson的代码不适合我。 对于那些在类似的情况,这里是我稍微不同的代码:

<TextField ref='myTextField'/>

使用它的价值

this.refs.myTextField.input.value

被接受的答案的策略是正确的,但这是一个广泛的例子,与当前版本的React和Material-UI一起工作。

数据stream应该是单向的:

  • initialState在MyForm控件的构造函数中被初始化
  • TextArea从这个初始状态填充
  • TextAreas的改变通过handleChangecallback被传播到state
  • state是从onClickcallback访问—现在它只是写入控制台。 如果你想添加validation它可以去那里。
 import * as React from "react"; import TextField from "material-ui/TextField"; import RaisedButton from "material-ui/RaisedButton"; const initialState = { error: null, // you could put error messages here if you wanted person: { firstname: "", lastname: "" } }; export class MyForm extends React.Component { constructor(props) { super(props); this.state = initialState; // make sure the "this" variable keeps its scope this.handleChange = this.handleChange.bind(this); this.onClick = this.onClick.bind(this); } render() { return ( <div> <div>{this.state.error}</div> <div> <TextField name="firstname" value={this.state.person.firstname} floatingLabelText="First Name" onChange={this.handleChange}/> <TextField name="lastname" value={this.state.person.lastname} floatingLabelText="Last Name" onChange={this.handleChange}/> </div> <div> <RaisedButton onClick={this.onClick} label="Submit!" /> </div> </div> ); } onClick() { console.log("when clicking, the form data is:"); console.log(this.state.person); } handleChange(event, newValue): void { event.persist(); // allow native event access (see: https://facebook.github.io/react/docs/events.html) // give react a function to set the state asynchronously. // here it's using the "name" value set on the TextField // to set state.person.[firstname|lastname]. this.setState((state) => state.person[event.target.name] = newValue); } } React.render(<MyForm />, document.getElementById('app')); 

(注意:您可能希望为每个MUI组件编写一个handleChangecallback以消除该丑陋的event.persist()调用。)

 class Content extends React.Component { render() { return ( <TextField ref={(input) => this.input = input} /> ); } _doSomethingWithData() { let inputValue = this.input.getValue(); } } 

下面是我想到的最简单的解决scheme,我们得到由material-ui textField创build的input的值:

  create(e) { e.preventDefault(); let name = this.refs.name.input.value; alert(name); } constructor(){ super(); this.create = this.create.bind(this); } render() { return ( <form> <TextField ref="name" hintText="" floatingLabelText="Your name" /><br/> <RaisedButton label="Create" onClick={this.create} primary={true} /> </form> )} 

希望这可以帮助。

Interesting Posts