簡體   English   中英

如何在React中強制重新渲染功能組件?

[英]How to force re-render function component in React?

當函數的變量之一更改時,我想重新渲染函數組件。 重要的是,此變量不隨prop一起提供。

我正在使用Material UI和React 16.8構建一個簡單的注冊表單。 它隨附了我嘗試使用的hooks API。 問題是,當輸入字段驗證的結果更改時,我想重新渲染組件。

export default function Register(props) {
 let emailError = false;
 const [email, setEmail] = useState('');
 const validateEmail = (email) => {
    if(email) {
      emailError = false;
    } else {
      emailError = true; // How to force re-render if email is not valid? 
    }
 } 

 return (<div>
            <TextField
                  error={emailError}
                  variant="outlined"
                  required
                  fullWidth
                  id="email"
                  label="Email Address"
                  onKeyUp={(ev) => validateEmail(ev.target.value)}
                  onChange={(ev) => setEmail(ev.target.value)}
                  name="email"
                  autoComplete="email"
                  aria-describedby="email-error-text"
                />
   </div>);
}

在這里您可以找到此組件的源代碼: https : //github.com/przemek-nowicki/auth-react-and-redux/blob/master/src/componnents/Register.js

您可能還應該在狀態中存儲錯誤布爾值。

 const [emailError, setEmailError] = useState(false); const [email, setEmail] = useState(''); useEffect(() => { setEmailError(!email); }, [email]); 

你可以用這個

const [emailError, setEmailError] = useState(false);
 const [email, setEmail] = useState('');
 const validateEmail = (email) => {
    if(email) {
      setEmailError(false);
    } else {
      setEmailError(true); 
    }
 } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM