最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Clear Textfield material-ui ReactJS - Stack Overflow

programmeradmin4浏览0评论

I have two text fields and a button using Material-UI, what I want to achieve is to clear the contents of the text fields when I click the button but I don't know how to do it, I'm new to React-JS.

This is the code I have:

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';

export default class CreateLinksave extends React.Component {
    render() {
        return (
            <div clssName="container">
                <div>
                    <TextField floatingLabelText="Receipt Desc" />
                </div>
                <div>
                    <TextField floatingLabelText="Triggers Required" />
                </div>
                <RaisedButton label="Clear" />
            </div>
        );
    }
};

Can someone please help me on this?

I have two text fields and a button using Material-UI, what I want to achieve is to clear the contents of the text fields when I click the button but I don't know how to do it, I'm new to React-JS.

This is the code I have:

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';

export default class CreateLinksave extends React.Component {
    render() {
        return (
            <div clssName="container">
                <div>
                    <TextField floatingLabelText="Receipt Desc" />
                </div>
                <div>
                    <TextField floatingLabelText="Triggers Required" />
                </div>
                <RaisedButton label="Clear" />
            </div>
        );
    }
};

Can someone please help me on this?

Share Improve this question edited Nov 7, 2017 at 16:03 M0nst3R 5,2831 gold badge27 silver badges38 bronze badges asked Nov 7, 2017 at 15:56 kennechukennechu 1,4229 gold badges25 silver badges37 bronze badges 2
  • You're going to have to add some component methods and bind an event to your raised button – Sterling Archer Commented Nov 7, 2017 at 15:58
  • What version of Material-UI are you using? – M0nst3R Commented Nov 7, 2017 at 16:04
Add a comment  | 

4 Answers 4

Reset to default 11

the text should be handled by the state

therefore you must only edit the state of the component so that your changes are shown

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';


export default class CreateLinksave extends React.Component {
  constructor(props){
    super(props);
    // initial state
    this.state = this.getDefaultState();
  }

  getDefaultState = () => {
    return { text1: '', text2: '' };
  }

  clear = () => {
    // return the initial state
    this.setState(this.getDefaultState())
  }

 render() {
  return (
    <div className="container">
      <div>
          <TextField
            value={this.state.text1}
            onChange={(e)=>{this.setState({text1: e.target.value})}}
            floatingLabelText="Receipt Desc"
          />
      </div>
        <div>
          <TextField
            onChange={(e)=>{this.setState({text2: e.target.value})}}
            value={this.state.text2}
            floatingLabelText="Triggers Required"
          />
        </div>
        // use the clear function
        <RaisedButton label="Clear" onClick={this.clear}/>
    </div>
  );
 }
}

If anyone has the same issue with the functional components in React, then you have to handle the value of the Textfield component with a state. Doesn't matter whether you use Formik library or not. Simple control the value property of the text field using a state variable.

import React from 'react';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';

const sampleTextControl = () => {
  const [value, setValue] = useState(''); //Initial value should be empty
  const handleSubmit = (e)=> {
    alert('The value: ' + value);
    setValue('');                        //To reset the textfield value
    e.preventDefault();
  }
  
  return ( 
    <form onSubmit={handleSubmit}>
      <Textfield id="standard-basic" value={value} onChange={(e)=>setValue(e.target.value)}/> 
      <Button variant="contained" type="submit" value="Submit">
        Submit
      </Button>
    </form >
  )
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

If you don't want to manage state for every text field then you should use refs:

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';

export default class CreateLinksave extends React.Component {
    constructor(props) {
      super(props);
      this.receiptRef = React.createRef('');
      this.triggersRef = React.createRef('');
    }

    handleClick = () => {
       this.receiptRef.current.value = null;
       this.triggersRef.current.value = null;
    }

    render() {
        return (
            <div clssName="container">
                <div>
                    <TextField floatingLabelText="Receipt Desc" />
                </div>
                <div>
                    <TextField floatingLabelText="Triggers Required" />
                </div>
                <RaisedButton label="Clear" onClick={this.handleClick}/>
            </div>
        );
    }
};

Just so there is a more up-to-date answer. I also find this is more on point for the question itself.

import { useState } from "react";
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Typography from '@mui/material/Typography';
import TextField from '@mui/material/TextField';

export default function FormClearExample() {

    const
        // create state const for form values
        [formName, setFormName] = useState(''),
        [formValue, setFormValue] = useState(''),

        handleSubmit = async (event) => {
            event.preventDefault();
            // do stuff here
            console.log(formName, formValue); // log form values
            // clear form values
            setFormName('');
            setFormValue('');
        };

    return (
        <Box sx={{ mt: 1 }} component="form" onSubmit={handleSubmit}>
            <Box sx={{ mt: 3 }}>
                <TextField
                    onChange={(e) => setFormName(e.target.value)} // update state const
                    margin="dense"
                    required
                    fullWidth
                    id="name"
                    label="Variable Name"
                    name="name"
                    value={formName} // use value from state const
                    autoFocus
                    size="small"
                />
                <TextField
                    onChange={(e) => setFormValue(e.target.value)} // update state const
                    margin="dense"
                    required
                    fullWidth
                    name="value"
                    value={formValue} // use value from state const
                    label="Value"
                    type="text"
                    id="description"
                    size="small"
                />
            </Box>
            <Typography sx={{ m: 1 }} component="h1" variant="h5">
                <Button
                    type="submit"
                >
                    Button Text
                </Button>
            </Typography>
        </Box>
    );
}
发布评论

评论列表(0)

  1. 暂无评论