我目前正在 Material Ui 文本欄位上使用 useRef 掛鉤,并且一直收到錯誤訊息Uncaught TypeError: Cannot read properties of undefined (reading 'focus'),我不知道如何解決。我的代碼如下所示:
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' } }} />
}
有人知道我的代碼有什么問題嗎?非常感謝。
uj5u.com熱心網友回復:
嘿,我認為最好先初始化 userRef() 上的值。
因此,將 useRef 視為 useState,狀態保存在下一次??渲染時,所以我認為您還應該決定要做什么 useRef,例如更新電子郵件或密碼?
例如: useRef('') 或null任何你想成為默認/初始值/狀態的東西。
那么也許你可以創建一個函式
const myFunction = () => {
// update the state or what you actually want to implement
}
然后我會myFunction在 useEffect 中運行。
希望有點幫助。
還要檢查這個:https ://dmitripavlutin.com/react-useref-guide/
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/478164.html
標籤:javascript 反应 dom 材料-ui
下一篇:如何動態地在運算式中應用運算式?
