简体   繁体   English

当 onChange 时 React Select 不会触发

[英]React Select does not trigger when onChange

I am trying to access the value of a Select with the event onChange so I can update another Select, but the Select doesn't trigger onChange.我试图通过事件 onChange 访问 Select 的值,以便我可以更新另一个 Select,但 Select 不会触发 onChange。 You can find the code in codesandbox :您可以在codeandbox 中找到代码:

import React, { useState } from "react";
import ReactDOM from "react-dom";
import { useForm, Controller } from "react-hook-form";
import {
  FormControl,
  Select,
  MenuItem,
  InputLabel,
  FormHelperText
} from "@material-ui/core";

function App() {
  const { handleSubmit, errors, control } = useForm();
  const onSubmit = (data) => {
    console.log(data);
  };
  const [test, setTest] = useState(0);
  const handleChange = (stateFunction, event) => {
    if (event) {
      console.log(event);
      setTest(event.target.value);
    }
  };
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <FormControl variant="outlined" required>
        <InputLabel>Test</InputLabel>
        <Controller
          as={
            <Select width={"300px"} onChange={handleChange(setTest, this)}>
              <MenuItem value="1">One</MenuItem>
              <MenuItem value="2">Two</MenuItem>
              <MenuItem value="3">Three</MenuItem>
            </Select>
          }
          control={control}
          defaultValue="1"
          name="brandId"
          rules={{ required: "Marca es requerido" }}
        />
        <FormHelperText error={true}>
          {errors.brand && errors.brand.message}
        </FormHelperText>
      </FormControl>

      <input type="submit" />
    </form>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Any idea where the problem is?知道问题出在哪里吗?

Thanks谢谢

you need to call function like onSubmit={() => handleSubmit(onSubmit)} .你需要调用像onSubmit={() => handleSubmit(onSubmit)}这样的函数。 In your current code, handleSubmit is called as soon as the component is rendered because you called it directly like this handleSubmit(onSubmit)在您当前的代码中, handleSubmit会在组件渲染后立即调用,因为您像这样直接调用它handleSubmit(onSubmit)

Final Output:最终输出:

在此处输入图片说明

Sandbox Link 沙盒链接

I have also edited the <SpecialInput/> component to handle input.我还编辑了<SpecialInput/>组件来处理输入。

Possible fix:可能的修复:


import React, { useState } from "react";
import ReactDOM from "react-dom";
import { useForm, Controller } from "react-hook-form";
import {
  FormControl,
  // SelectField,
  MenuItem,
  Select,
  InputLabel,
  FormHelperText
} from "@material-ui/core";
import SpecialInput from "./SpecialInput";
function App() {
  const { handleSubmit, errors, control } = useForm();
  const onSubmit = (data) => {
    console.log("hi");
  };
  const [test, setTest] = useState(0);
  const [selectedItem, setItem] = useState(1);
  const handleChange = (stateFunction, event) => {
    if (event) {
      event.preventDefault();
      console.log("hi");
      // setTest(event.target.value);
      console.log("test:", test);
    }
  };

  const onTextChange = (event) => {
    setTest(event.target.value);
  };

  return (
    <form onSubmit={(event) => handleChange(onSubmit, event)}>
      <FormControl variant="outlined" required>
        <InputLabel>Test</InputLabel>
       
        <Controller
          render={(props) => (
            <Select
              value={selectedItem}
              onChange={(event) => setItem(event.target.value)}
            >
              <MenuItem value="1">One</MenuItem>
              <MenuItem value="2">Two</MenuItem>
              <MenuItem value="3">Three</MenuItem>
            </Select>
          )}
          control={control}
          defaultValue="1"
          name="brandId"
          rules={{ required: "Marca es requerido" }}
        />
        <FormHelperText error={true}>
          {errors.brand && errors.brand.message}
        </FormHelperText>
      </FormControl>
      <SpecialInput handleChange={onTextChange} test={test} />
      <input type="submit" />
      <h1>{`Test Value: ${test}`}</h1>
      <h1>{`Select Value: ${selectedItem}`}</h1>
    </form>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM