反应useState挂钩变量值不会在输入onChange事件上更新

时间:2019-10-22 05:22:45

标签: javascript reactjs

react useState钩子不会使用React功能组件在输入onChange事件上更新

const [email, setEmail] = useState("");
// i'm not able to set input value in useeffect using this code
<GridItem xs={12} sm={12} md={4}>
  <CustomInput
    labelText="Email address"
    id="email-address"
    formControlProps={{
      fullWidth: true
    }}

    value={email}
    onChange={evt => setEmail(evt.target.value)}
  />
</GridItem>

3 个答案:

答案 0 :(得分:0)

您的职能在哪里?

onChange={e => this.setEmail(e)} // use arrow function to bind this

setEmail = (e) => {
  yourSetFunction({[e.target.name]:e.target.value}) // assuming you give you input a name
}

答案 1 :(得分:0)

App.js

function App() {
  const [email, setEmail] = React.useState("");
  const handleChange = e => {
    setEmail(e.target.value);
  };
  return (
    <div>
      <h4>{email}</h4>
      <CustomInput handleChange={handleChange} />
    </div>
  );
}

CustomInput.js

import React from "react";

function CustomInput(props) {
  return (
    <div>
      <input type="text" onChange={props.handleChange} />
    </div>
  );
}

export default CustomInput;

答案 2 :(得分:0)

const [email, setEmail] = useState(null);
const handleChange = (e) => {
  setEmail(e.target.value);
}
// i'm not able to set input value in useeffect using this code
<GridItem xs={12} sm={12} md={4}>
  <CustomInput
    labelText="Email address"
    id="email-address"
    formControlProps={{
      fullWidth: true
    }}

    value={email}
    onChange={handleChange}
  />
</GridItem>