I have a Datepicker of Material that opens if you click on the textfield it belongs to. If you try to select another textfield while the datepicker is opened it will target/focus back to the datepicker.

Note: This issue is also for targeting nothing, it will refocus the datepicker again after closing it.

Example Demo: https://stackblitz.com/edit/react-b4xpki?file=demo.tsx

Code:

`

export default function BasicDatePicker() {
  const [value, setValue] = React.useState<Dayjs | null>(null);
  const [open, setOpen] = React.useState(false);

  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <TextField placeholder='Click here while datepicker is opened' fullWidth={true} sx={{mb:2, mr: 2}}/>
      <DatePicker
        label="Basic example"
        value={value}
        onChange={(newValue) => {
          setValue(newValue);
        }}
        open={open}
        onOpen={() => setOpen(true)}
        onClose={() => setOpen(false)}
        renderInput={(props) => (
          <TextField {...props} onClick={(e) => setOpen(true)} />
        )}
      />
    </LocalizationProvider>
  );
}

So how to reproduce to problem?

  1. Click op the datepicker (not the icon)
  2. Click on another textfield
  3. Watch how the target/focus is back on the datepicker

推荐答案

You can create focus named state so can control in onFocus at <TextField />

firstly, create focus named state:

const [focus, setFocus] = useState(false);

TextField: if open is false in onFocus, currentTarget shouldn't be focus.

 <TextField
     {...props}
      onFocus={(e) => {
          setFocus(open);
          if (!open) {
             e.currentTarget.blur();
             return;
          }
      }}
      focused={focus}
      onClick={(e) => setOpen((prev) => !prev)}
 />

if the value changes in DatePicker, focus should be true.

<DatePicker
    label="Basic example"
    value={value}
    onChange={(newValue) => {
      setValue(newValue);
       setFocus(true);
    }}
    ...otherProps
/>

link: https://stackblitz.com/edit/react-b4xpki-rirdxn?file=demo.tsx

Javascript相关问答推荐

还原器未正确更新状态

在运行时使用Next JS App Router在服务器组件中运行自定义函数

JavaScript是否有多个`unfined`?

DOM不自动更新,尽管运行倒计时TS,JS

让chart.js饼图中的一个切片变厚?

使用父标签中的Find函数查找元素

JWT Cookie安全性

用另一个带有类名的div包装元素

每隔3个项目交替显示,然后每1个项目交替显示

我们是否可以在reactjs中创建多个同名的路由

有角粘桌盒阴影

Played link-Initialize.js永远显示加载符号

在传单的图像覆盖中重新着色特定 colored颜色 的所有像素

如何缩小函数中联合返回类型的范围

从客户端更新MongoDB数据库

单击子按钮时将活动切换类添加到父分区

VITE版本中的内联SVG

更改所有验证组件文本和背景 colored颜色

如果用户的页面宽度低于某个阈值,如何使用js更改html页面中的css文件

如何 Select 名称正在更改的DOM元素