问题
I'm using react-date-picker, but on mobile the native keyboard shows up when clicked causing the date-picker to open on top, which doesn't look great. The online solution is to put the readonly attribute on the input field the date picker is bind with. But the read-date-picker component won't let me pass that prop...
Any nice solutions for this?
回答1:
So I ended up modifying the input-element in the componentDidMount lifecycle, like so;
document.getElementsByTagName("input")[0].setAttribute("readonly", "readonly");
This prevents the native visual keyboard on my phone to display. However it creates this "not allowed" red ugly cursor on desktop when hovering the input field, so I fixed that with by targeting my date-picker input.
.react-datepicker-wrapper input[readonly]{cursor: pointer;}
I welcome alternative solutions though.
回答2:
The readOnly
is a good option to prevent the browser showing the keyboard and the typing on mobile. With the readonly
seted you will still be able to launch a click event on it.
When, talking about the react-date-picker module the this will be also useful in non-mobile devices.
It is possible to add the option readOnly={true}
, but it will disable completely the datepicker inputs on all devices, as we can see on the following issues:
- Datepicker does not open with readOnly=true #1443
- make disable or readonly input field #961
Also, you will need to handle the onClick
event and I don't think that this is a good idea.
Current workaround
At the moment, the solution to make the keyboard disabled on mobile and set the readOnly
for all datePickers inputs will be edit the input properties on the component componentDidMount event:
componentDidMount() {
const datePickers = document.getElementsByClassName("react-datepicker__input-container");
Array.from(datePickers).forEach((el => el.childNodes[0].setAttribute("readOnly", true)))
};
回答3:
A variation on Caroline Waddell's answer that got me unblocked on react-datepicker 2.8.0
. The id of the date picker element is date-picker-input
so modifying the the attribute after getting it by the id:
componentDidMount() {
document.getElementById('date-picker-input').setAttribute('readonly', 'readonly');
}
Did the trick for me if you have more than one input
on the page.
来源:https://stackoverflow.com/questions/48805053/hide-native-keyboard-on-mobile-when-using-react-date-picker