如何在输入类型日期中设置占位符[React]

김정수*_*김정수 9 html javascript css reactjs

我想知道如何在输入日期中设置占位符。

\n

这是我的代码

\n
<input type="text" onChange={(e) => { setbirth(moment(e.target.value).format('YYYYMMDD')) }} placeholder="\xec\x83\x9d\xeb\x85\x84\xec\x9b\x94\xec\x9d\xbc" onFocus="(this.type = 'date')" onBlur="(this.type='text')" />\n
Run Code Online (Sandbox Code Playgroud)\n

我已经查看了这个问题,但是使用此代码\n会引发错误。

\n
onfocus="(this.type='date')" onblur="(this.type='text')"\n\n\nWarning: Expected `onFocus` listener to be a function, instead got a value of `string` type.\nWarning: Expected `onBlur` listener to be a function, instead got a value of `string` type.\n
Run Code Online (Sandbox Code Playgroud)\n

有什么办法可以改而不报错吗?

\n

小智 8

useRef此处不推荐,因为它无助于重新渲染组件,因此不会更改输入type。更好的方法是将其初始化为“text”类型,并根据onFocus和上的事件更改类型onBlur。对于您的用例,请查看下面的代码。

export default function App() {
  return (
    <div>
      <input
        type="text"
        onChange={(e) => console.log(e.target.value)}
        onFocus={(e) => (e.target.type = "date")}
        onBlur={(e) => (e.target.type = "text")}
      />
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)


小智 5

import React , { useRef } from "react";

const App= () => {
  const ref = useRef();
  return (
    <div>
      <input
        type="date"
        ref={ref}
        onChange={(e) => console.log(e.target.value)}
        onFocus={() => (ref.current.type = "date")}
        onBlur={() => (ref.current.type = "date")}
      />
    </div>
  );
}
export default  App
Run Code Online (Sandbox Code Playgroud)