簡體   English   中英

如何從 material-ui TextField、DropDownMenu 組件獲取數據?

[英]How get data from material-ui TextField, DropDownMenu components?

我創建了表單,我有幾個 TextField、DropDownMenu 材料用戶界面組件,問題是我如何從一個 obj 中的所有 TextFields、DropDownMenus 收集所有數據並將其發送到服務器上。 對於 TextField,它有 TextField.getValue() 返回輸入的值。 但我無法理解如何使用它。

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處理程序。 當它被調用時,將這些輸入的新值保存在你的Content組件的state中。 在渲染中,從state檢索這些值並將它們作為value prop 傳遞。 請參閱受控組件

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檢索所有輸入的值並將它們發送到服務器。

你也可以使用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()

這里所有的解決方案都是基於類組件的,但我猜大多數最近學過 React 的人(像我一樣),此時使用的是函數式組件。 所以這里是基於功能組件的解決方案。

使用 ReactJs 的 useRef 鈎子和 TextField 的 inputRef 屬性。

    import React, { useRef, Component } from 'react'
    import { TextField, Button } from '@material-ui/core'
    import SendIcon from '@material-ui/icons/Send'

    export default function MultilineTextFields() {
    const valueRef = useRef('') //creating a refernce for TextField Component

    const sendValue = () => {
        return console.log(valueRef.current.value) //on clicking button accesing current value of TextField and outputing it to console 
    }

    return (
        <form noValidate autoComplete='off'>
        <div>
            <TextField
            id='outlined-textarea'
            label='Content'
            placeholder='Write your thoughts'
            multiline
            variant='outlined'
            rows={20}
            inputRef={valueRef}   //connecting inputRef property of TextField to the valueRef
            />
            <Button
            variant='contained'
            color='primary'
            size='small'
            endIcon={<SendIcon />}
            onClick={sendValue}
            >
            Send
            </Button>
        </div>
        </form>
    )
    }

flson 的代碼對我不起作用。 對於那些處於類似情況的人,這是我的略有不同的代碼:

<TextField ref='myTextField'/>

使用

this.refs.myTextField.input.value

接受答案的策略是正確的,但這里有一個適用於當前版本的 React 和 Material-UI 的通用示例。

數據流應該是單向的:

  • initialState 在 MyForm 控件的構造函數中初始化
  • TextArea是從這個初始狀態填充的
  • 對 TextAreas 的更改通過handleChange回調傳播到state
  • state是從onClick回調訪問的——現在它只是寫入控制台。 如果你想添加驗證,它可以去那里。
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 組件編寫一個handleChange回調以消除那個丑陋的event.persist()調用。)

自從這里提出問題以來,很長一段時間后才面臨這個問題。 在檢查 material-ui 代碼時,我發現它現在可以通過inputRef屬性訪問。

...
<CssTextField
  inputRef={(c) => {this.myRefs.username = c}}
  label="Username"
  placeholder="xxxxxxx"
  margin="normal"
  className={classes.textField}
  variant="outlined"
  fullWidth
/>
...

然后像這樣訪問值。

  onSaveUser = () => {
    console.log('Saving user');
    console.log(this.myRefs.username.value);
  }

這是我想出的最簡單的解決方案,我們獲得了 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>
        )}

希望這可以幫助。

我不知道你們所有人,但為了我自己的懶惰目的,我只是通過 ID 從“文檔”中獲取文本字段,並將這些值設置為我的后端 JS 函數的參數:

 //index.js <TextField id="field1" ... /> <TextField id="field2" ... /> <Button ... onClick={() => { printIt(document.getElementById('field1').value, document.getElementById('field2').value) }}> //printIt.js export function printIt(text1, text2) { console.log('on button clicked'); alert(text1); alert(text2); };

它工作得很好。

嘗試這個,

import React from 'react';
import {useState} from 'react';

import TextField from '@material-ui/core/TextField';

const Input = () => {
    const [textInput, setTextInput] = useState('');

    const handleTextInputChange = event => {
        setTextInput(event.target.value);
    };
    
    return(
        <TextField
            label="Text Input"
            value= {textInput}
            onChange= {handleTextInputChange}
        />
    );
}

export default Input;

如果上面的代碼不清楚,請說明。

首先,我們創建一個狀態來存儲名為textInput的文本輸入,並為其分配值 ''。

然后我們返回一個材質 UI <TextField />組件,其value屬性設置為textInput狀態。 這樣做我們在<TextField />顯示textInput的當前值。 textInput值的任何更改都將更改<TextField />value屬性,由 React 提供。

然后我們使用<TextField />onChange屬性在每次<TextField /> value屬性的改變時運行一個處理函數。 這個處理函數是一個存儲在常量handleTextInputChange 中的箭頭函數。 它將事件作為參數。 onChange屬性運行處理程序函數時,它會將事件作為參數發送給處理程序函數。

<TextField />值存儲在event.target.value 中 然后我們使用狀態的setTextInput方法將狀態設置為<TextField />value屬性。 因此,此更改反映在<TextField />value屬性是textInput狀態的值。

因此,輸入到<TextField />的數據存儲在狀態textInput 中,以備需要時使用。

2020 年對於 TextField,通過功能組件:

const Content = () => {
   ... 
      const textFieldRef = useRef();

      const readTextFieldValue = () => {
        console.log(textFieldRef.current.value)
      }
   ...
  
      return(
       ...
       <TextField
        id="myTextField"
        label="Text Field"
        variant="outlined"
        inputRef={textFieldRef}
       />
       ...
      )

}

請注意,這不是完整的代碼。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM