反應中的 v-if 是什么?我試過了,但是當加載資料發生變化時,我的加載類的 div 不起作用,所以 div 不會重新渲染自己。代碼在這里:
{
loading &&
<div className="loading"></div>
}
我正在用一個函式改變加載,這個函式與 onclick 事件一起作業。
我所有的代碼:
import React from "react";
import axios from "axios";
export class LoginPage extends React.Component{
render(){
let username = '',
password = '',
loading = false
function login(){
loading = true;
console.log(loading)
}
return (
<div className="App">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css"
integrity="sha512-Fo3rlrZj/k7ujTnHg4CGR2D7kSs0v4LLanw2qksYuRlEzO tcaEPQogQ0KaoGN26/zrn20ImR1DfuLWnOo7aBA=="
crossOrigin="anonymous" referrerpolicy="no-referrer"/>
{
loading &&
<div className="loading"></div>
}
<div className="login">
<h1>Login/Register</h1>
<div>
<i className="fas fa-user"></i>
<input type="text" onChange={(e) => username = e.target.value} placeholder="Username" maxLength="15"/>
</div>
<div>
<i className="fas fa-lock"></i>
<input type="Password" placeholder="Password" onChange={(e) => password = e.target.value} maxLength="18"/>
</div>
<button onClick={() => login()}>Login/Register</button>
</div>
</div>
);
}
}
uj5u.com熱心網友回復:
我建議您閱讀有關 React State 的內容,這段代碼中的某些內容是錯誤的。但是,讓我們解決您的問題。
首先將此變數添加到狀態,然后用setState, 更改它以觸發重新渲染:
export class LoginPage extends React.Component{
constructor(props) {
super(props);
this.state = {
loading: false
};
}
render(){
let username = '',
password = '',
function login(){
this.setState({ loading: true })
console.log(loading)
}
// your return will stay the same
}
}
uj5u.com熱心網友回復:
V-if 是一個 Vue 指令,因此它不適用于 React。要在 React 中正確更新 UI,您必須創建加載變數作為狀態變數。如果您將組件創建為類組件,那么您應該創建加載變數作為狀態物件的一部分,并使用如下處理函式更新狀態:
class LoadingComponent extends React.Component {
//state variable, each update to this object will update your UI
//and rerender the component tree under that updated component
state = {
loading: false
}
//handler for the onClick event you are triggering to update you state
//and rerender your component
handleOnClick = () => {
const isLoading = this.state.loading
this.setState({loading: !isLoading})
}
//... rest of your component
}
如果您使用的是功能組件,那么您應該使用 React 提供的 useState 鉤子創建加載變數,并使用您為該變數創建的設定器更新它:
import {useState} from 'react'
const LoadingComponent = () => {
//State variable declaration
const [loading, setLoading] = useState(false)
//handler for the onClick event
//you can directly put the setLoading call in the onClick prop of the component
//but I separate it here for more clear explanation
const handleOnClick = () => {
setLoading(!loading)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/415601.html
標籤:
上一篇:如何在Javascript中使用正則運算式不拆分數學方程字串中的小數點
下一篇:如何在影像內的div內定位文本?
