简体   繁体   中英

Manually lose focus from TextField select component, Material UI & React

I have a select input which I create by using TextField component from Material-UI lib. I need to manually lose focus after some option been selected. I tried to use a reference to the TextField using 'inputRef' prop, which works great but when I try to fire blur() function on this.selectInput.current like I did here but without MaterialUI lib.

 class Select extends React.Component { constructor(props) { super(props) this.state = { selected: '' } this.inputRef = React.createRef(); this.onChangeHandler = this.onChangeHandler.bind(this) } onChangeHandler(e){ this.inputRef.current.blur() this.setState({ selected: e.target.value }) } render() { const {selected} = this.state; return ( <select value={selected} onChange={this.onChangeHandler} ref={this.inputRef}> <option value=''>Please select</option> <option value='1'>One</option> <option value='2'>Two</option> </select> ) } } ReactDOM.render(<Select />, document.querySelector("#app"))
 <script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script> <div id="app"></div>

I got an error that blur() function does not exist. I understand that Material UI used custom el. to create UI and I target just a div or whatever. So the question is it another way to get the exact behavior (lose focus on the select event) when using TextField component or maybe I did something wrong?

Material UI v1.3.1 | React v16.4.2

Try to define onClose method with the following body:

onClose() {
    setTimeout(() => {
        document.activeElement.blur();
    }, 0);
}

and then pass this method to onClose prop of the select element.

I faced similar issue with blur event in react material-ui Select component

import Select from '@material-ui/core/Select';
<Select
...
onClose={()=>{
    setTimeout(() => {
        setOpen(false)
        handleSubmit();
    }, 0);
}}
/>

The simplest way, it's just rerender it with a new key:

import { useState } from 'react';
import { TextField } from '@mui/material';
import { nanoid } from '@reduxjs/toolkit';
...
const [inputKey, setInputKey] = useState<string>(nanoid());
...
// You need to blur here, for example.
const someFunc = () => {
    setInputKey(nanoid())
}
...
<TextField select key={inputKey} />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM