【问题标题】:Getting empty string from HTML input event in Firefox从 Firefox 中的 HTML 输入事件中获取空字符串
【发布时间】:2022-01-06 21:22:28
【问题描述】:

所选选项未反映。我有一个下拉列表,它是controlled 输入。 Whenever any option is chosen then getting empty string from event.target.value = <empty string>

Google Chrome 中不会出现此问题。一切正常,但在 Firefox 中却没有。

这是我的代码:

<select
    id="location"
    required
    name="location_id"
    className="form-control form-control-sm"
    value={item.location_id} // <-- state data
    onChange={(e) => {
      setVariantsLocations(
         e,
         product.bundle_variant_id,
         bv.sku,
         item.id
         );
     }}>
      <option value="">--Select--</option>
      {bv.locations?.map((loc) => {
             return (
               <option
                  value={loc?.id}
                  disabled={loc.quantity === 0}>
                     {loc?.code} [Q: {loc.quantity}]
               </option>
              );
             })
       }
</select>
setVariantsLocations = (e, parentSku, childSku, item_id) => {
    console.log(e.target.value) // <empty string>
}

【问题讨论】:

  • 你使用的是什么版本的 React?通过console.log(JSON.stringify(e.target.value)) 记录了什么?您是否尝试过将事件e 直接记录在匿名回调处理程序中 传递给setVariantsLocations?认为您可以创建一个 running 代码框来重现我们可以实时检查和调试的问题?
  • React v16.14.0 & 从 console.log(JSON.stringify(e.target.value)) 获取 ''
  • 谢谢。那你可以试试做一个codeandbox吗?

标签: html reactjs google-chrome firefox


【解决方案1】:

首先,确认您的事件处理程序正在被调用,而不是目标值为空 - 最简单的方法是将您的 console.log 更改为:

console.log(`Event: '${e.currentTarget.value}'`)

我在想,因为您有一个受控组件,所以您设置 selectvalue 的逻辑在某种程度上是不正确的,因此您没有“完成循环”并获得更改进入 DOM。尝试将其简化为由useState() 控制的简单字符串,看看是否有帮助,不要“关闭”setVariantsLocations 的参数;例如:

const [selectedId, setSelectedId] = useState(undefined); 

...

  const setVariantsLocations = (e) => {
    console.log(`Event: '${e.target.value}'`);
    setSelectedId(e.target.value);
  };

...

<select
  id="location"
  required
  name="location_id"
  className="form-control form-control-sm"
  value={selectedId} // <-- state data
  onChange={setVariantsLocations}
>

现在您已经获得了最简单的受控组件。如果这在所有浏览器中都有效,那么开始重新增加复杂性,看看哪里开始出错了。

【讨论】:

    猜你喜欢
    • 2011-12-08
    • 2020-12-19
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-07
    • 2011-09-27
    相关资源
    最近更新 更多