我有我制作的這個示例代碼框,但是,在我原來的代碼框中已經有很多值了。我只是重現了我遇到的問題。
Codesandbox:https ://codesandbox.io/s/youthful-firefly-40mig3?file=/src/App.js
我在App.js其中定義了一些我需要的值,然后將其傳遞給其他 2 個組件。
<div className="App">
{/* some codes here */}
<h1>App page</h1>
Initial Amount: 1000
<br />
Total Amount: {totalAmount}
<br />
----------------------------------------------------------
<h6>Passing the total amount and the second input here</h6>
<Second input2={input2} setInput2={setInput2} />
----------------------------------------------------------
<h6>Third here</h6>
<Third totalAmount={totalAmount} />
</div>
我Second.js在計算totalAmount. 這是我遇到的問題。這里required沒有被識別。如果此欄位為空,我只是想阻止用戶提交表單。如果某個欄位為空,是否有其他方法不會提交,或者如果它為空,則將輸入欄位保留為 1?
const Second = ({ input2, setInput2 }) => {
return (
<div>
Second here
<form>
<input
fullWidth
value={input2}
onChange={(e) => setInput2(e.target.value)}
required
/>
</form>
</div>
);
};
export default Second;
這是Third.js我傳遞totalAmount和添加更多值的地方,例如nameand age。在這里name和age正在被識別。這也是我在這里提交所有內容的地方。
const Third = ({ totalAmount }) => {
const [name, setName] = useState("");
const [age, setAge] = useState(0);
const handleSubmit = (e) => {
e.preventDefault();
try {
console.log(name, age, totalAmount);
} catch (err) {
console.log(err);
}
};
return (
<div>
Third here
<form onSubmit={handleSubmit}>
<label>Name</label>
<input
fullWidth
value={name}
onChange={(e) => setName(e.target.value)}
required
/>
<br /> <br />
<label>Age</label>
<input
fullWidth
value={age}
onChange={(e) => setAge(e.target.value)}
required
/>
<br /> <br />
<button type="submit">submit</button>
</form>
</div>
);
};
export default Third;
uj5u.com熱心網友回復:
您可以將其input2作為一個傳遞prop給Third.js,在那里您可以檢查是否input2不存在然后不要提交值。
在App.js傳遞input2給Third組件。
<Third totalAmount={totalAmount} input2={input2} />
然后Third.js檢查該input2值是否存在。
const Third = ({ totalAmount, input2 }) => {
const [name, setName] = useState("");
const [age, setAge] = useState(0);
const handleSubmit = (e) => {
e.preventDefault();
if (input2) {
try {
console.log(name, age, totalAmount);
} catch (err) {
console.log(err);
}
}else {
alert('Please enter the second value');
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/475508.html
標籤:javascript 反应
上一篇:洗掉3個div內的只讀屬性
下一篇:使用ref訪問按鈕
