onChange属性在我在文本字段中输入任何内容时都会重置文本字段。

huangapple go评论71阅读模式
英文:

The onChange property reset the textfield every time when I type anything in the textfield

问题

以下是您要翻译的内容:

"I'm trying to create a SignUp authentication page with firebase, So when I'm try to type anything in the textfield every time the text field got reset, I cant able to find the problem. But the main problem I found that with the onChange property. Please fix the issue why the textfield state change every time.

The SignUp page code:

import React, { useState, useContext } from 'react';
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';
import Link from '@mui/material/Link';
import Grid from '@mui/material/Grid';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Container from '@mui/material/Container';
import { styled } from '@mui/material';
import Logo from '../assets/QpiVolta-Logo.png';
import { useTheme, IconButton } from '@mui/material';
import { tokens } from '../theme';
import { Person, Lock, Mail, Visibility, VisibilityOff } from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';
import { UserAuth } from '../context/AuthContext';

const SignUp = () => {
  // ... 代码内容 ...
}

export default SignUp;

我已经翻译了代码部分,如果您需要进一步的帮助,请告诉我。

英文:

I'm trying to create a SignUp authentication page with firebase, So when I'm try to type anything in the textfield every time the text field got reset, I cant able to find the problem. But the main problem I found that with the "onChange" property. Please fix the issue why the textfield state change every time.
The SignUp page code:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

import React,{useState,useContext} from &#39;react&#39;;
import Button from &#39;@mui/material/Button&#39;;
import TextField from &#39;@mui/material/TextField&#39;;
import Link from &#39;@mui/material/Link&#39;;
import Grid from &#39;@mui/material/Grid&#39;;
import Box from &#39;@mui/material/Box&#39;;
import Typography from &#39;@mui/material/Typography&#39;;
import Container from &#39;@mui/material/Container&#39;;
import { styled } from &#39;@mui/material&#39;;
import Logo from &#39;../assets/QpiVolta-Logo.png&#39;
import { useTheme,IconButton } from &#39;@mui/material&#39;;
import { tokens } from &#39;../theme&#39;;
import {Person,Lock, Mail, Visibility, VisibilityOff} from &#39;@mui/icons-material&#39;;
import { useNavigate } from &#39;react-router-dom&#39;;
import { UserAuth } from &#39;../context/AuthContext&#39;;
const SignUp = () =&gt; {
const theme = useTheme();
const colors = tokens(theme.palette.mode);
const [showPassword, setShowPassword] = useState(false);
const handleClickShowPassword = () =&gt; setShowPassword((show) =&gt; !show);
const handleMouseDownPassword = (event) =&gt; {
event.preventDefault();
};
const [email, setEmail] = useState(&quot;&quot;)
const [password, setPassword] = useState(&quot;&quot;)
const [name,setName] = useState(&quot;&quot;)
const [error, setError] = useState(&quot;&quot;)
const {signUp} = UserAuth()
const navigate = useNavigate()
const handleSubmit= async(e) =&gt; {
e.preventDefault()
try {
await signUp(email,password)
setError(&#39;&#39;)
navigate(&#39;/&#39;) 
}
catch (error) {
console.log(error)
setError(error.message)
}
}
const RootStyle = styled(&quot;div&quot;)({
backgroundColor:&quot;#d4cbf6&quot;,
background:`${colors.primary[400]} !important`,
height: &quot;100vh&quot;,
display: &quot;flex&quot;,
placeItems: &quot;center&quot;,
});
const logoStyle = {
height: &#39;80px&#39;,
};
const CssTextField = styled(TextField)({
&#39;&amp; label.Mui-focused&#39;: {
color: `${colors.pinkAccent[500]}`,
},
&#39;&amp; .MuiInput-underline:after&#39;: {
borderBottomColor:  `${colors.pinkAccent[500]}`,
},
&#39;&amp; .MuiOutlinedInput-root&#39;: {
&#39;&amp; fieldset&#39;: {
borderColor: &#39;grey&#39;,
},
&#39;&amp;:hover fieldset&#39;: {
borderColor: `${colors.pinkAccent[500]}`,
},
&#39;&amp;.Mui-focused fieldset&#39;: {
borderColor: `${colors.pinkAccent[500]}`,
},
},
});
return (
&lt;RootStyle&gt;
&lt;Container  maxWidth=&quot;sm&quot; &gt;
&lt;Box
sx={{
marginTop: 8,
display: &#39;flex&#39;,
flexDirection: &#39;column&#39;,
alignItems: &#39;center&#39;,            
}}
&gt;
&lt;img component=&quot;img&quot; src={Logo} style={logoStyle}  /&gt;
&lt;Typography component=&quot;h1&quot; variant=&quot;h2&quot; color={colors.grey[100]} &gt;
Create an account&lt;span style={{ color:`${colors.pinkAccent[500]}`}}&gt;.&lt;/span&gt;
&lt;/Typography&gt;
&lt;Box component=&quot;form&quot;  onSubmit={handleSubmit} sx={{ mt: 2 , mb:2}}&gt;
&lt;Grid container spacing={3} &gt;
&lt;Grid item xs={12} sm={6} &gt;
&lt;Box sx={{ display: &#39;flex&#39;, alignItems: &#39;flex-end&#39; }}&gt;
&lt;Person sx={{ color: &#39;action.active&#39;, mr: 1, my: 0.5 }} /&gt;
&lt;CssTextField  
fullWidth
label=&quot;First Name&quot; 
id=&quot;FirstName&quot;
name=&quot;FirstName&quot;
autoComplete=&quot;family-name&quot;
variant=&#39;standard&#39; 
value={name}
onChange={(e)=&gt; setName(e.target.value)}
/&gt;
&lt;/Box&gt;
&lt;/Grid&gt;
&lt;Grid item xs={12} sm={6}&gt;
&lt;Box sx={{ display: &#39;flex&#39;, alignItems: &#39;flex-end&#39; }}&gt;
&lt;Person sx={{ color: &#39;action.active&#39;, mr: 1, my: 0.5 }} /&gt;
&lt;CssTextField
fullWidth
id=&quot;lastName&quot;
label=&quot;Last Name&quot;
name=&quot;lastName&quot;
autoComplete=&quot;family-name&quot;
variant=&#39;standard&#39; 
/&gt;
&lt;/Box&gt;
&lt;/Grid&gt;
&lt;Grid item xs={12}&gt;
&lt;Box sx={{ display: &#39;flex&#39;, alignItems: &#39;flex-end&#39; }}&gt;
&lt;Mail sx={{ color: &#39;action.active&#39;, mr: 1, my: 0.5 }} /&gt;
&lt;CssTextField
required
fullWidth
id=&quot;email&quot;
label=&quot;Email Address&quot;
name=&quot;email&quot;
value={email}
autoComplete=&quot;email&quot;
variant=&#39;standard&#39; 
onChange={(e) =&gt; {
console.log(e.target.value); // add this line
setEmail(e.target.value);
}}
/&gt;
&lt;/Box&gt;
&lt;/Grid&gt;
&lt;Grid item xs={12}&gt;
&lt;Box sx={{ display: &#39;flex&#39;, alignItems: &#39;flex-end&#39; }}&gt;
&lt;Lock sx={{ color: &#39;action.active&#39;, mr: 1, my: 0.5 }} /&gt;
&lt;CssTextField
required
fullWidth
name=&quot;password&quot;
label=&quot;Password&quot;
id=&quot;password&quot;
autoComplete=&quot;new-password&quot;
type={showPassword ? &#39;text&#39; : &#39;password&#39;}
variant=&#39;standard&#39;
value={password}
onChange={(e) =&gt; setPassword(e.target.value)}
InputProps={{
endAdornment: (
&lt;IconButton
aria-label=&quot;toggle password visibility&quot;
onClick={handleClickShowPassword}
onMouseDown={handleMouseDownPassword}
&gt;
{showPassword ? &lt;Visibility /&gt; : &lt;VisibilityOff /&gt;}
&lt;/IconButton&gt;
),
}}
/&gt;
&lt;/Box&gt;
&lt;/Grid&gt;
&lt;/Grid&gt;
&lt;Button
type=&quot;submit&quot;
fullWidth
variant=&quot;contained&quot;
sx={{ mt: 3, mb: 2 }}
&gt;
Sign Up
&lt;/Button&gt;
&lt;Grid container justifyContent=&quot;flex-end&quot;&gt;
&lt;Grid item&gt;
&lt;Link href=&quot;/Login&quot; variant=&quot;body2&quot; sx={{color:&quot;grey&quot;}}&gt;
Already have an account? Sign in
&lt;/Link&gt;
&lt;/Grid&gt;
&lt;/Grid&gt;
&lt;/Box&gt;
&lt;/Box&gt;
&lt;/Container&gt;
&lt;/RootStyle&gt;    
)
}
export default SignUp

<!-- end snippet -->

答案1

得分: 2

你不应该将 CssTextFieldRootStyled 组件放在 SignUp 组件内部。将它们放在外部,它就会起作用。

import TextField, { TextFieldProps } from '@mui/material/TextField';

type StyledTextFieldProps = TextFieldProps & {
    colors?: any,
};
const CssTextField =
    styled(TextField, {
        shouldForwardProp: (prop) => prop !== 'colors',
    })`
    StyledTextFieldProps
    ((props) => ({
        '& label.Mui-focused': {
            color: `${props.colors.pinkAccent[500]}`,
        },
        '& .MuiInput-underline:after': {
            borderBottomColor: `${props.colors.pinkAccent[500]}`,
        },
        '& .MuiOutlinedInput-root': {
            '& fieldset': {
                borderColor: 'grey',
            },
            '&:hover fieldset': {
                borderColor: `${props.colors.pinkAccent[500]}`,
            },
            '&.Mui-focused fieldset': {
                borderColor: `${props.colors.pinkAccent[500]}`,
            },
        },
    }));
    
const RootStyle = styled('div')((props) => ({
    backgroundColor: '#d4cbf6',
    background: `${props.colors.primary[400]} !important`,
    height: '100vh',
    display: 'flex',
    placeItems: 'center',
}));

const SignUp = () => {
    const colors = tokens(theme.palette.mode);

    return (
        <RootStyle colors={colors}>
            <CssTextField
                fullWidth
                label="First Name"
                id="FirstName"
                name="FirstName"
                autoComplete="family-name"
                variant="standard"
                colors={colors}
                onChange={(e) => setName(e.target.value)}
            />
        </RootStyle>
    );
};
英文:

You should not put CssTextField and RootStyled components inside SignUp component. Put it outside and it works

import TextField, { TextFieldProps } from &#39;@mui/material/TextField&#39;;
type StyledTextFieldProps = TextFieldProps &amp; {
colors?: any,
};
const CssTextField =
styled(TextField, {
shouldForwardProp: (prop) =&gt; prop !== &#39;colors&#39;,
}) &lt;
StyledTextFieldProps &gt;
((props) =&gt; ({
&#39;&amp; label.Mui-focused&#39;: {
color: `${props.colors.pinkAccent[500]}`,
},
&#39;&amp; .MuiInput-underline:after&#39;: {
borderBottomColor: `${props.colors.pinkAccent[500]}`,
},
&#39;&amp; .MuiOutlinedInput-root&#39;: {
&#39;&amp; fieldset&#39;: {
borderColor: &#39;grey&#39;,
},
&#39;&amp;:hover fieldset&#39;: {
borderColor: `${props.colors.pinkAccent[500]}`,
},
&#39;&amp;.Mui-focused fieldset&#39;: {
borderColor: `${props.colors.pinkAccent[500]}`,
},
},
}));
const RootStyle = styled(&#39;div&#39;)((props) =&gt; ({
backgroundColor: &#39;#d4cbf6&#39;,
background: `${props.colors.primary[400]} !important`,
height: &#39;100vh&#39;,
display: &#39;flex&#39;,
placeItems: &#39;center&#39;,
}));
const SignUp = () =&gt; {
const colors = tokens(theme.palette.mode);
return (
&lt;RootStyle colors={colors}&gt;
&lt;CssTextField
fullWidth
label=&quot;First Name&quot;
id=&quot;FirstName&quot;
name=&quot;FirstName&quot;
autoComplete=&quot;family-name&quot;
variant=&quot;standard&quot;
colors={colors}
onChange={(e) =&gt; setName(e.target.value)}
/&gt;
&lt;/RootStyle&gt;
);
};

答案2

得分: 1

尝试为每个文本字段添加值属性,类似如下:

<CssTextField
    fullWidth
    label="First Name"
    id="FirstName"
    name="FirstName"
    autoComplete="family-name"
    variant='standard'
    onChange={(e) => setName(e.target.value)}
    value={name}
/>

对于其他具有onChange属性的文本字段也要执行相同操作。

英文:

Try adding value prop as well for each text field. Something like below

&lt;CssTextField  
fullWidth
label=&quot;First Name&quot; 
id=&quot;FirstName&quot;
name=&quot;FirstName&quot;
autoComplete=&quot;family-name&quot;
variant=&#39;standard&#39; 
onChange={(e)=&gt; setName(e.target.value)}
value={name}
/&gt;

do this for other text field as well where onChange prop is present.

huangapple
  • 本文由 发表于 2023年3月9日 15:56:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75681801.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定