Gok*_*ram 5 javascript reactjs react-select
大家好,我遇到了有关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>
);
}
Run Code Online (Sandbox Code Playgroud)
考虑这段代码(查看评论):
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>
);
}
Run Code Online (Sandbox Code Playgroud)
正如 @a.mola 所说 -setValue钩子是异步的,并且value当事件触发时变量尚未更新onBlur,因此它保存之前设置的值。
我不确定您想在这次onBlur活动中实现什么目标,这可能不是合适的地方。
如果您需要以value某种方式输出 - 您可以在该return部分中执行此操作(如上面的代码中所做的那样)。
如果您需要验证value或根据其新选择的值执行某些操作 - 您可以在onSelect函数中执行此操作。
| 归档时间: |
|
| 查看次数: |
1187 次 |
| 最近记录: |