2015-04-22 43 views
34

Tôi tạo biểu mẫu, tôi có một số thành phần MaterialField, DropDownMenu, bao gồm câu hỏi là cách tôi có thể thu thập tất cả dữ liệu từ tất cả TextFields, DropDownMenus trong một obj và gửi nó trên máy chủ. Đối với TextField, nó có TextField.getValue() Trả về giá trị của đầu vào. Nhưng tôi không thể hiểu cách sử dụng nó.Cách lấy dữ liệu từ các thành phần TextField, thành phần DropDownMenu?

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; 

Tôi muốn gửi nó trên máy chủ bằng phương thức _handleClick.

Trả lời

39

Thêm trình xử lý onChange vào từng thành phần TextFieldDropDownMenu của bạn. Khi được gọi, hãy lưu giá trị mới của các đầu vào này trong số state của thành phần Content của bạn. Trong kết xuất, hãy truy lục các giá trị này từ state và chuyển các giá trị đó thành giá trị value chống đỡ. Xem Controlled Components.

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> 
     ) 
    } 

}); 

Bây giờ tất cả các bạn phải làm trong phương pháp _handleClick của bạn là lấy các giá trị của tất cả các nguyên liệu đầu vào của bạn từ this.state và gửi chúng đến các máy chủ.

Bạn cũng có thể sử dụng React.addons.LinkedStateMixin để làm cho quá trình này dễ dàng hơn. Xem Two-Way Binding Helpers. Đoạn mã trên trở thành:

var Content = React.createClass({ 

    mixins: [React.addons.LinkedStateMixin], 

    getInitialState: function() { 
     return { 
      textFieldValue: '' 
     }; 
    }, 

    render: function() { 
     return (
      <div> 
       <TextField valueLink={this.linkState('textFieldValue')} /> 
      </div> 
     ) 
    } 

}); 
+0

Cần lưu ý rằng trình xử lý 'onChange' cho thành phần DropDownMenu sẽ được gọi với các đối số sau: _event_, _key_, _payload_. Tải trọng là giá trị 'MenuItem' đã chọn. Khóa là chỉ mục 'MenuItem'. Xem nguồn: https://github.com/callemall/material-ui/blob/master/src/DropDownMenu/DropDownMenu.jsx – Mido

+1

Trích dẫn tài liệu phản ứng: ReactLink không còn được dùng như React v15. Đề xuất là đặt rõ ràng giá trị và xử lý thay đổi, thay vì sử dụng ReactLink. https://facebook.github.io/react/docs/two-way-binding-helpers.html – sebastienbarbier

65

sử dụng câu trả lời chấp nhận/này là câu trả lời khác (đã bị xóa) câu hỏi

@karopastal

thêm một thuộc tính ref-<TextField /> thành phần và cuộc gọi của bạn getValue() trên đó, như sau:

Thành phần:

<TextField ref="myField" /> 

Sử dụng getValue: Mã

this.refs.myField.getValue() 
+1

Phương pháp này là tốt hơn –

+0

điều này có vẻ là cách thích hợp để sử dụng tài liệu-UI tài liệu. Đã làm "this.refs.myField.getDOMNode.getValue()" nhưng đã hoàn toàn sai, cảm ơn câu trả lời. – rosnk

+2

@flson nó không hoạt động với trình đơn thả xuống, bạn làm cách nào để thả xuống. Làm việc với phần còn lại của thành phần mặc dù. Đã mở một câu hỏi khác, nếu bạn có câu trả lời, hãy giúp tôi. liên kết: http://stackoverflow.com/questions/32633272/need-to-get-value-of-dropdown-menu-without-using-onchange-callback-material-u – rosnk

4

flson đã không làm việc cho tôi. Đối với những người trong tình huống tương tự, đây là mã hơi khác nhau của tôi:

<TextField ref='myTextField'/>

nhận được giá trị của nó sử dụng

this.refs.myTextField.input.value

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

    _doSomethingWithData() { 
     let inputValue = this.input.getValue(); 
    } 
} 
+2

Đây là gì, họ nên đặt nó ở đâu? Nó làm gì? Câu trả lời này không hữu ích nếu không có ngữ cảnh bổ sung? – Adam

+1

Bạn nói đúng. Tôi đã sửa câu trả lời. –

+0

Thêm một số giải thích không chỉ là mã. –

2

Chiến lược của câu trả lời được chấp nhận là đúng, nhưng đây là một ví dụ tổng quát làm việc với phiên bản hiện tại của React và Material-UI.

Dòng chảy của dữ liệu nên có một chiều:

  • các initialState được khởi tạo trong constructor của sự kiểm soát MyForm
  • các TextArea s được dân cư từ trạng thái ban đầu này
  • thay đổi đối với textareas được truyền đến số state qua cuộc gọi lại handleChange.
  • số state được truy cập từ số gọi lại onClick --- ngay bây giờ nó chỉ ghi vào bảng điều khiển. Nếu bạn muốn thêm xác nhận, nó có thể đến đó.
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')); 

(Lưu ý:. Bạn có thể muốn viết một handleChange callback mỗi MŨI phần để loại bỏ sự xấu xí event.persist() cuộc gọi)

1

Đây là giải pháp đơn giản nhất tôi đã đưa ra, chúng tôi nhận được giá trị của đầu vào được tạo bởi material-ui textField:

 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> 
     )} 

hy vọng điều này sẽ hữu ích.

Các vấn đề liên quan