简体   繁体   English

默认值不会在输入中更新

[英]Default value doesn't get updated inside input

In a list of certain records where I'm populating in the dropdown of an input component.在我在输入组件的下拉列表中填充的某些记录的列表中。 The default value is set on page loading but, I need to update it on click event of a button.默认值是在页面加载时设置的,但是我需要在按钮的单击事件中更新它。 Refer to the code below.请参阅下面的代码。

Home.js主页.js

const allList = [
    { id: "1", value: "Fruits" },
    { id: "2", value: "Vegetables" },
    { id: "3", value: "Grains" },
    { id: "4", value: "Milk" },
    { id: "5", value: "Meat" },
    { id: "6", value: "Fish" },
    { id: "7", value: "Pulses" }
  ];

const [itemList, setItemList] = useState(allList);
const [newValue, setNewValue] = useState(allList[0].value)

// I want to set the value on click of cancel button
const handleCancel = (e) => {
    setNewValue(allList[2].value)
    setPopup(false);
  };

return (
<>
<DataList
            defaultValue={newValue}
            list="itemListOptions"
            id="itemList"
            placeholder="Search/select items"
            data={itemList}
            onSelectionChange={itemChanged}
          ></DataList>
{popup === true ? (
        <Popup okbtnClick={handleOK} canclebtnclick={handleCancel} />
      ) : null}
</>
)

DataList.js数据列表.js

        <input
         defaultValue={props?.defaultValue ?? ""}
         className="form-control cpselect"
         id={props?.id ?? ""}
         list={props?.list ?? ""}
         placeholder={props?.placeholder ?? ""}
         onChange={props?.onSelectionChange ?? ""}
        />
        <datalist key={props.id} id={props?.list ?? ""}>
         {props.data.map((d) => {
          return <option key={d.id} id={d.id} value={d.value}></option>;
         })}
        </datalist>

My intention is to change the defaultValue inside the input field, on click of cancel button.我的意图是在单击取消按钮时更改输入字段内的 defaultValue。 Here it loads the first element and on click event should load third element.在这里它加载第一个元素,点击事件应该加载第三个元素。 What is the best optimal solution?最好的最优解是什么?

Please refer to the Codesandbox link: https://codesandbox.io/s/clever-rumple-ig0wwj请参考 Codesandbox 链接: https ://codesandbox.io/s/clever-rumple-ig0wwj

What you want to do is to use value instead of defaultValue .您要做的是使用value而不是defaultValue

defaultValue property is configured in such a way that it reads the prop only once and then creates an inner state that handles changes. defaultValue属性的配置方式是它只读取一次 prop,然后创建一个处理更改的内部状态。

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

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