首页 > 解决方案 > React select npm onBlur 函数返回错误

问题描述

大家好,我对 react-select onBlur 函数有疑问,我做了很多研究并调查了相关的 git 问题,但仍然找不到答案。OnBlur 函数没有获取选定的值,onBlur 中的值显示为未定义。如果答案可用,请建议我。谢谢您的帮助

Codesanbox 链接供参考:

编辑奇怪的太阳 uojxs

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>
  );
}

标签: javascriptreactjsreact-select

解决方案


考虑这段代码(查看评论):

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>
  );
}

编辑轻松-ellis-y1z2d

正如@a.mola 所说 -setValue钩子是异步的,并且在事件触发value时变量尚未更新,因此它保存先前设置的值。onBlur

我不确定你想在onBlur活动中实现什么,它可能不是正确的地方。

如果您需要以value某种方式输出 - 您可以在return部件内执行此操作(如上面的代码中所做的那样)。

如果您需要value根据新选择的值验证或执行某些操作 - 您可以在onSelect函数中执行此操作。


推荐阅读