MUI 自定义文本字段失去对状态更改的关注

Jab*_*ian 14 javascript reactjs material-ui react-hooks use-state

我正在使用MUI库来创建我的React Js应用程序。

在这里,我使用受控文本字段组件来创建一个简单的搜索 UI。

但有一点奇怪。组件Text Field在其值更改后失去焦点。 这是我第一次遇到这个问题。我以前从未遇到过这个问题。

怎么会发生这种事?以及解决办法是什么。

这是代码和游乐场: https: //codesandbox.io/s/mui-autocomplete-lost-focus-oenoo

breakpoint type注意:如果我从代码中删除,Text Field组件在其值更改后仍然会失去焦点。

cjl*_*750 32

这是因为您在另一个组件内定义了一个组件,因此每次渲染该组件时都会重新创建组件定义(并且每次用户在输入中键入时都会渲染您的组件)。

两种解决方案:

  1. 不要将其作为一个单独的组件。

    代替:

    const MyComponent = () => {
      const MyInput = () => <div><input /></div>; // you get the idea
    
      return (
        <div>
          <MyInput />
        </div>
      );
    };
    
    Run Code Online (Sandbox Code Playgroud)

    做:

    const MyComponent = () => {    
      return (
        <div>
          <div><input /></div> {/* you get the idea */}
        </div>
      );
    };
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在其父组件之外定义组件:

    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>
      );
    };
    
    Run Code Online (Sandbox Code Playgroud)


Sch*_*nic 9

请注意组件的按键,如果将动态值设置为按键道具,也会导致焦点丢失。这是一个例子


{people.map(person => (
    <div key={person.name}>
      <Input type="text" value={person.name} onChange={// function which manipulates person name} />
    </div>
))}

Run Code Online (Sandbox Code Playgroud)


小智 7

适用于 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;
Run Code Online (Sandbox Code Playgroud)