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

后端 未结 10 2008
遥遥无期
遥遥无期 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: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 (
                
    {this.state.error}
    ); } 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(, document.getElementById('app'));

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

提交回复
热议问题