[英]MUI Custom Text Field loses focus on state change
在這里,我使用受控的文本字段組件來創建一個簡單的搜索 UI。
但有一點奇怪。 Text Field
組件在其值更改后失去焦點。 這是我第一次面對這個問題。 我以前從未遇到過這個問題。
這怎么可能發生? 什么是解決方案。
這是代碼和游樂場: https://codesandbox.io/s/mui-autocomplete-lost-focus-oenoo ?
注意:如果我從代碼中刪除breakpoint type
, Text Field
組件在其值更改后仍然會失去焦點。
對於 MUI V5
將自定義樣式的代碼移到組件之外
例如:
import React from 'react';
import { useTheme, TextField, styled } from '@mui/material';
import { SearchOutlined } from '@mui/icons-material';
interface SearchInputProps { placeholder?: string; onChange: (event: React.ChangeEvent<HTMLInputElement>) => void; value: string; dataTest?: string; }
const StyledSearchInput = styled(TextField)(({ theme }: any) => { return {
'& .MuiOutlinedInput-root': {
borderRadius: '0.625rem',
fontSize: '1rem',
'& fieldset': {
borderColor: `${theme.palette.text.secondary}`
},
'&.Mui-focused fieldset': {
borderColor: `${theme.palette.primary}`
}
} }; });
const SearchInput: React.FC<SearchInputProps> = ({ placeholder = 'Search...', onChange, value, dataTest, ...props }) => { const theme = useTheme();
return (
<StyledSearchInput
{...props}
onChange={onChange}
placeholder={placeholder}
variant="outlined"
value={value}
inputProps={{ 'data-testid': dataTest ? dataTest : 'search-input' }}
InputProps={{
startAdornment: (
<SearchOutlined
sx={{ color: theme.palette.text.secondary, height: '1.5rem', width: '1.5rem' }}
/>
)
}}
/> ); };
export default SearchInput;
這是因為您在另一個組件中定義了一個組件,因此每次呈現組件時都會重新創建組件定義(並且每次用戶輸入輸入時都會呈現您的組件)。
兩種解決方案:
不要讓它成為一個單獨的組件。 代替:
const MyComponent = () => { const MyInput = () => <div><input /></div>; // you get the idea return ( <div> <MyInput /> </div> ); };
做:
const MyComponent = () => { return ( <div> <div><input /></div>; // you get the idea </div> ); };
在其父組件之外定義組件:
const MyInput = ({value, onChange}) => ( <div> <input value={value} onChange={onChange} /> </div> ); const MyComponent = () => { const [value, setValue] = useState(''); return ( <div> <MyInput value={value} onChange={event => setValue(event.target.value)} /> </div> ); };
請注意組件的鍵,如果將動態值設置為鍵屬性,也會導致焦點丟失。 這是一個例子
{people.map(person => (
<div key={person.name}>
<Input type="text" value={person.name} onChange={// function which manipulates person name} />
</div>
))}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.