簡體   English   中英

select 默認值不起作用 reactjs

[英]select default value is not working reactjs

我正在嘗試將 select 默認值轉換為 select 輸入,但輸入無法識別該值,直到我手動更改它。 默認情況下,我將“全部”設置為默認值。 這是我的代碼和 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

您使用的庫有一個錯誤

源代碼顯示value prop 僅在componendDidUpdate中檢查,但初始渲染時不會調用此掛鈎

我寧願使用不同的庫

一個簡單的解決方法是 set 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>
  );
}

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM