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

后端 未结 10 1910
遥遥无期
遥遥无期 2021-01-31 01:13

I create form, I have several TextField, DropDownMenu material-ui components included, question is how I can collect all data from all TextFields, DropDownMenus in one obj and s

相关标签:
10条回答
  • 2021-01-31 01:38

    In 2020 for TextField, via functional components:

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

    Note that this isn't complete code.

    0 讨论(0)
  • 2021-01-31 01:40

    Add an onChange handler to each of your TextField and DropDownMenu elements. When it is called, save the new value of these inputs in the state of your Content component. In render, retrieve these values from state and pass them as the value prop. See 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>
            )
        }
    
    });
    

    Now all you have to do in your _handleClick method is retrieve the values of all your inputs from this.state and send them to the server.

    You can also use the React.addons.LinkedStateMixin to make this process easier. See Two-Way Binding Helpers. The previous code becomes:

    var Content = React.createClass({
    
        mixins: [React.addons.LinkedStateMixin],
    
        getInitialState: function() {
            return {
                textFieldValue: ''
            };
        },
    
        render: function() {
            return (
                <div>
                    <TextField valueLink={this.linkState('textFieldValue')} />
                </div>
            )
        }
    
    });
    
    0 讨论(0)
  • 2021-01-31 01:41
    class Content extends React.Component {
        render() {
            return (
                <TextField ref={(input) => this.input = input} />
            );
        }
    
        _doSomethingWithData() {
            let inputValue =  this.input.getValue();
        }
    }
    
    0 讨论(0)
  • 2021-01-31 01:42

    The strategy of the accepted answer is correct, but here's a generalized example that works with the current version of React and Material-UI.

    The flow of data should be one-way:

    • the initialState is initialized in the constructor of the MyForm control
    • the TextAreas are populated from this initial state
    • changes to the TextAreas are propagated to the state via the handleChange callback.
    • the state is accessed from the onClick callback---right now it just writes to the console. If you want to add validation it could go there.
    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'));
    

    (Note: You may want to write one handleChange callback per MUI Component to eliminate that ugly event.persist() call.)

    0 讨论(0)
  • 2021-01-31 01:43

    flson's code did not work for me. For those in the similar situation, here is my slightly different code:

    <TextField ref='myTextField'/>

    get its value using

    this.refs.myTextField.input.value

    0 讨论(0)
  • 2021-01-31 01:53

    Here's the simplest solution i came up with, we get the value of the input created by 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>
            )}
    

    hope this helps.

    0 讨论(0)
提交回复
热议问题