[英](MUI Textfield) Uncaught TypeError: Cannot read properties of undefined (reading 'focus')
I am currently using the useRef hook on the Material Ui Textfield, and I kept getting the error Uncaught TypeError: Cannot read properties of undefined (reading 'focus')
, and I have no idea how to solve.我目前正在 Material Ui 文本字段上使用 useRef 挂钩,并且一直收到错误
Uncaught TypeError: Cannot read properties of undefined (reading 'focus')
,我不知道如何解决。 My code looks like this:我的代码如下所示:
const LoginTextField = styled(TextField)({
'& .MuiInput-underline:after': {
borderBottomColor: 'white',
},
'& .MuiOutlinedInput-root': {
'& fieldset': {
borderColor: '#263238',
},
input: { color: 'white' },
backgroundColor: '#263238'
}
});
export default function test() {
const userRef = useRef();
const [loginEmail, setLoginEmail] = useState('');
useEffect(() => {
userRef.current.focus();
}, [])
<LoginTextField label='Email' variant='outlined' onChange={(e) => setLoginEmail(e.target.value)}
inputRef={userRef} InputLabelProps={{ style: { color: 'white' } }} />
}
Anybody has an idea what is wrong with my code?有人知道我的代码有什么问题吗? Much thanks.
非常感谢。
hey I think it would be better if you first initialise the value on the userRef().嘿,我认为最好先初始化 userRef() 上的值。
So think of useRef as the useState, where the state is saved on the next render so I think you should decide also what the useRef you want to do, like update the email or password?因此,将 useRef 视为 useState,状态保存在下一次渲染时,所以我认为您还应该决定要做什么 useRef,例如更新电子邮件或密码?
For instance: useRef('') or null
or whatever you want to be the default/ initial value/ state in your case.例如: useRef('') 或
null
或任何您想成为默认/初始值/状态的东西。
Then maybe you could create a function那么也许你可以创建一个函数
const myFunction = () => {
// update the state or what you actually want to implement
}
Then I would run myFunction
inside the useEffect.然后我会在 useEffect 中运行
myFunction
。
Hope that kinda helps.希望有点帮助。
Check also this: https://dmitripavlutin.com/react-useref-guide/还要检查这个: https ://dmitripavlutin.com/react-useref-guide/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.