反应物料重置表格值

时间:2020-03-09 09:29:11

标签: javascript reactjs react-material

我正在使用带钩的反应材料,我想对材料表格进行重置。

我一直在尝试设置状态,但是没有任何变化

<form className="create-account-form" autoComplete="off" onSubmit={onSubmit}>
  <FormControl
    error={!!errorText.first_name}
    variant="outlined"
    size="small"
    fullWidth
  >
    <InputLabel>First Name</InputLabel>
    <OutlinedInput
      name="first_name"
      className="create-account-input"
      labelWidth={90}
      disabled={loading}
      onChange={event => handleChange("first_name", event)}
    />
  </FormControl>
  <Button
    type="submit"
    className="submit-button"
    color="primary"
    variant="contained"
  >
    Submit
  </Button>
</form>;
//my state varibles

const [signUpData, setSignUpData] = useState({
  first_name: ""
});
const handleChange = (field, event) => {
  if (event) {
    setSignUpData({
      ...signUpData,
      [field]: event.target ? event.target.value : event
    });
  }
};

提交后,我想清除输入字段中的数据。

const onSubmit = e => {
  e.preventDefault();
   setSignUpData((prev) => (prev.first_name = "",));

  // clearfunction()
};

3 个答案:

答案 0 :(得分:1)

加载初始状态

const init = {first_name: ''};
const [signUpData, setSignUpData] = useState(init)

const onSubmit = (e) => {
  e.preventDefault();
  // do submit logic
  setSignUpData(init)
}

答案 1 :(得分:0)

使对象重置或设置初始值

const initial_value={

first_name:""}

然后setSignUpData(...initial_value);,因为您有一个输入使用了这种形状 或setSignUpData(initial_value);

答案 2 :(得分:0)

您看到的,您实际上并没有将状态变量绑定到输入字段

import React, { useContext, useState } from "react";
import "./styles.css";

const themes = {
  light: {
    name: "light",
    foreground: "black",
    background: "white"
  },
  dark: {
    name: "dark",
    foreground: "white",
    background: "black"
  }
};

const ThemeContext = React.createContext(null);

const Toolbar = props => {
  const theme = useContext(ThemeContext) || {};
  console.log(`Toolbar theme`, theme);
  return (
    <div
      style={{
        height: 60,
        backgroundColor: theme.background,
        color: theme.foreground
      }}
    >
      <div>{theme.name}</div>
    </div>
  );
};

export default function App() {
  const [currentTheme, setCurrentTheme] = useState(themes.light);

  const toggleTheme = theme => {
    setCurrentTheme(theme);
  };

  console.log(`currentTheme`, currentTheme);

  return (
    <div className="App">
      <ThemeContext.Provider value={currentTheme}>
        <div>
          <button onClick={() => toggleTheme(themes.light)}>light</button>
          <button onClick={() => toggleTheme(themes.dark)}>dark</button>
        </div>
        {/* Toolbar() */}
        {/* {Toolbar()} */}
        <Toolbar />
      </ThemeContext.Provider>
    </div>
  );
}