javascript - React select npm onBlur 函数返回错误
问题描述
大家好,我对 react-select onBlur 函数有疑问,我做了很多研究并调查了相关的 git 问题,但仍然找不到答案。OnBlur 函数没有获取选定的值,onBlur 中的值显示为未定义。如果答案可用,请建议我。谢谢您的帮助
Codesanbox 链接供参考:
import React, { useState } from "react";
import Select from "react-select";
import "./styles.css";
export default function App() {
const [value, setValue] = useState();
const options = [
{
label: "first option",
value: 1
},
{
label: "second option",
value: 2
},
{
label: "third option",
value: 3
}
];
const onSelect = (value) => {
setValue(value);
};
const onBlurValue = (value) => {
console.log(value);
};
return (
<div>
<Select
value={options.label}
options={options}
onChange={onSelect}
blurInputOnSelect
onBlur={onBlurValue}
/>
</div>
);
}
解决方案
考虑这段代码(查看评论):
import React, { useState } from "react";
import Select from "react-select";
import "./styles.css";
export default function App() {
const [value, setValue] = useState();
const options = [
{
label: "first option",
value: 1
},
{
label: "second option",
value: 2
},
{
label: "third option",
value: 3
}
];
// destructuring the object to get 'value' property
// (the passed object looks like { label, value } )
const onSelect = ({value}) => {
// here the 'value' variable is being set
console.debug("selected value:", value )
setValue(value);
};
// destructuring event object to get 'target' property
const onBlurValue = ({target}) => {
console.log("onBlur target value:", target.value);
// the value is not updated yet, so it holds the previously set value
console.log("onBlur value:", value || "undefined");
};
return (
<div>
Current value is: {value || "undefined" }
<Select
// the value prop does nothing here
// value={options.label}
options={options}
onChange={onSelect}
blurInputOnSelect
onBlur={onBlurValue}
/>
</div>
);
}
正如@a.mola 所说 -setValue
钩子是异步的,并且在事件触发value
时变量尚未更新,因此它保存先前设置的值。onBlur
我不确定你想在onBlur
活动中实现什么,它可能不是正确的地方。
如果您需要以value
某种方式输出 - 您可以在return
部件内执行此操作(如上面的代码中所做的那样)。
如果您需要value
根据新选择的值验证或执行某些操作 - 您可以在onSelect
函数中执行此操作。
推荐阅读
- batch-file - 用户输入文本时批处理文件不断崩溃
- c - c中的rand()函数是否遵循非确定性算法
- java - 为什么我会得到一个 ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0?
- r - 使用 interact_plot 更改图形的字体(包交互)
- sql-server - 如何避免在重新运行加载数据的 SSIS 包时将数据(重复)重新插入 SQL Server 表?
- c++ - 如何避免对编译后无法访问的正在运行的代码部分进行运行时检查?
- r - 根据条件和按组更改列的值
- javascript - 构造函数在反应应用程序的“构建器模式”中的类的多个实例中运行一次
- python-3.x - 图像和标签在 TFRecord 中不对应
- python - 无法使用 python 过滤器返回预期的输出