[英]React's Ref value not updating on change
我正在嘗試根據輸入字段是否為空的條件來設置按鈕的禁用屬性。 但是,即使在輸入中輸入時,ref 也不會更新使按鈕保持禁用狀態的值。 我怎樣才能使 ref 更新值以便條件也更新?
// imports
export default function Card() {
const fields = useRef<{ [key: string]: { [key: string]: HTMLInputElement } }>({});
return (
//Rest of table
<td className="flex-wrap px-2 text-sm text-gray-500">
{/* Weight input */}
<input
type="number"
inputMode="decimal"
className="w-12 pl-1 text-base rounded-sm bg-gravel-100"
ref={(el) => {
if (!fields.current[section.id]) fields.current[section.id] = {};
fields.current[section.id][exercise.name] = el as HTMLInputElement;
}}
/>
</td>
<td>
<button
id={idx.toString()}
{/* This condition doesn't change */}
disabled={
(loading && section.id + exercise.name === loadingExercise) ||
fields.current[section.id][exercise.name].value === ""
}
onClick={() => {
if (
typeof fields.current[section.id][exercise.name].valueAsNumber ===
"number"
) {
setWeightInDb(
section.name,
exercise.name,
fields.current[section.id][exercise.name].valueAsNumber
);
setLoadingExercise(section.id + exercise.name);
}
fields.current[section.id][exercise.name].value = "";
console.log(
"Field value" + fields.current[section.id][exercise.name].value
);
}}
type="button"
className="flex items-center justify-center w-8 h-8 border border-transparent rounded shadow-md disabled:shadow-none disabled:opacity-25"
>
{section.id + exercise.name === loadingExercise && loading ? (
(console.log(exercise.name, loadingExercise),
(<Spinner height={20} width={20} />))
) : (
<CheckIcon className="w-6 h-6 p-1 text-center text-nomad-700" />
)}
{/* <LoadingSpring loading={false} /> */}
</button>
);
}
我建議您為按鈕內的禁用道具提供一個 state 變量。 這樣,當 state 變量發生變化時,按鈕將重新呈現。
import { useState } from "react";
const [isButtonDisabled, setIsButtonDisabled] = useState(false);
<button disabled={isButtonDisabled}>This is a Button</button>
現在實施一種方法,您可以在其中檢查您喜歡的任何條件。 當某些變量或道具發生變化時,您還可以使用 useEffect 來更新 state 變量,如下所示:
import { useEffect } from "react";
useEffect(() => {
if (someProp === true) {
setIsButtonDisabled(true);
} else {
setIsButtonDisabled(false);
}
}, [someProp]);
只要您更改 state,該按鈕就會重新呈現並顯示為已禁用或未禁用。
e.g.
setIsButtonDisabled(true);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.