reactjs 选择默认值不是工作React

2fjabf4q  于 2022-12-26  发布在  React
关注(0)|答案(2)|浏览(159)

我尝试选择一个默认值到一个选择输入,但输入不承认该值,直到我手动更改它。默认情况下,我设置"所有"作为我的默认值。这里是我的代码和codesandbox链接:

import "./styles.css";
import React, { useState, useEffect } from "react";
import { FormField } from "react-form-input-fields";
import "react-form-input-fields/dist/index.css";

export default function App() {
  let [type, setType] = useState("All");
  const types = [
    { label: "All", value: "All" },
    { label: "Afganistan", value: "Afganistan" },
    { label: "Albania", value: "Albania" },
    { label: "Algeria", value: "Algeria" },
    { label: "American Samoa", value: "American Samoa" },
    { label: "Andorra", value: "Andorra" },
    { label: "Angola", value: "Angola" }
  ];

  function handletype(e) {
    setType(e);
  }

  return (
    <div className="App">
      {/* <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2> */}
      <FormField
        type="select"
        value={type}
        option={types}
        label={"Select your type"}
        keys={"label"}
        handleOnChange={(value) => handletype(value)}
      />
    </div>
  );
}

链接:
https://codesandbox.io/s/select-problem-ykplcm

6ju8rftf

6ju8rftf1#

您使用的库有错误
源代码显示value属性仅在componendDidUpdate中检查,但初始呈现时不会调用此钩子
我宁愿使用其他库

gmxoilav

gmxoilav2#

一个简单的解决方法是设置label= [hook value]

import "./styles.css";
import React, { useState, useEffect } from "react";
import { FormField } from "react-form-input-fields";
import "react-form-input-fields/dist/index.css";

export default function App() {
  let [type, setType] = useState("All");

  return (
    <div className="App">
      {/* <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2> */}
      <FormField
        type="select"
        value={type}
        option={types}
        label={"Select your type"}
        keys={"label"}
        handleOnChange={(value) => handletype(value)}
      />
    </div>
  );
}

Demo

相关问题