Mui 输入字段在设置状态时重置

Mui input field resets while setting state

我最近对 ​​material 设计很感兴趣,并找到了一个名为 mui 的库,我猜它基本上是 material ui 的一个端口来做出反应。一切正常,但当我设置字段重置的任何状态时除外。

import { FilledInput, Input, OutlinedInput, TextField } from "@mui/material";
import { useState } from "react";
import { useDropzone } from "react-dropzone";
import { alpha, createTheme, styled } from '@mui/material/styles';
import MdEditor from 'react-markdown-editor-lite';
import Blog from "../components/Blogs/Blog/Blog";
import MarkdownIt from "markdown-it";
import 'react-markdown-editor-lite/lib/index.css';

export const AddBlog = () => {


    const [title, setTitle] = useState(""); //Setting this resets the text field


    const CssTextField = styled(TextField)({

        '& label': {
            color: 'white !important',
        },

        '& input': {
            color: 'white !important',
        },


        '& .MuiOutlinedInput-root': {
            '& fieldset': {
                borderColor: 'white',
            },
            '&:hover fieldset': {
                borderColor: 'white',
            },
            '&.Mui-focused fieldset': {
                borderColor: '#0582CA',
            },
        }
    });

    const handleInput = (e : React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => {
        setTitle(e.target.value);
    }


    return (
        
            <div className="flex flex-col items-center gap-5 my-4">
                <CssTextField label="Tytuł" color="primary" className="md:w-1/3 w-full" onChange={(e) => handleInput(e)} />
               
            </div>

        


    )

}

每次有状态数据更改时,文本输入都会重置,值也会重置,因此您无法输入任何内容

所以,是的,我找到了解决方案。原因是每当我设置状态时,组件都会重新呈现,CssTextField 变量也会重新呈现。我将 CssTextField 移出了组件,现在它可以工作了。这是正确的代码。

const CssTextField = styled(TextField)({

        '& label': {
            color: 'white !important',
        },

        '& input': {
            color: 'white !important',
        },


        '& .MuiOutlinedInput-root': {
            '& fieldset': {
                borderColor: 'white',
            },
            '&:hover fieldset': {
                borderColor: 'white',
            },
            '&.Mui-focused fieldset': {
                borderColor: '#0582CA',
            },
        }
    });

export const AddBlog = () => {


    const [title, setTitle] = useState(""); 

    const handleInput = (e : React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => {
        setTitle(e.target.value);
    }


    return (
        
            <div className="flex flex-col items-center gap-5 my-4">
                <CssTextField label="Tytuł" color="primary" className="md:w-1/3 w-full" onChange={(e) => handleInput(e)} />
               
            </div>

        


    )

}