慕標(biāo)琳琳
2022-12-29 16:21:23
我在調(diào)用函數(shù)時(shí)遇到問(wèn)題。這個(gè)函數(shù)在主App.js文件中,它作為 prop 傳遞給不同的組件。如果表單驗(yàn)證返回 true 但我的代碼不起作用,我需要調(diào)用此函數(shù)。App.js 中的函數(shù) function getAlarm() { let message = document.getElementById("text").value; let hour = document.getElementById("hours").value; let minute = document.getElementById("minutes").value; //Add id to alarm let id; if(time.alarms.length > 0 ){ id = Math.max(...time.alarms.map((alarm) => alarm.id)) + 1 }else{ id = 1; } //Create new alarm object const newAlarm = { id: id, message: message, hour: hour, minute: minute };作為道具傳遞給組件<SetAlarm getInfo={getAlarm} />在這個(gè)組件中,我有一些小表格,其中有一些驗(yàn)證。為了更好地理解,我還將向您展示表單和這些功能。形式<form onSubmit={validateForm}> <FontAwesomeIcon icon={faTimesCircle} className="closeIcon" onClick={() => setAlarm(false)} /> <h3>Please set your alarm</h3> <label htmlFor="text">Message</label> <input type="text" id="text" autoComplete="off" autoFocus="on" /> <div className="flex"> <div className="inputNumber"> <label htmlFor="hours">Hour</label> <input type="number" id="hours" value={validate.hours} onChange={updateHours} /> <div id="errHours"></div> </div> <div className="inputNumber"> <label htmlFor="minutes">Minute</label> <input type="number" id="minutes" onChange={updateMinutes} /> <div id="errMinutes"></div> </div> </div> <button onClick={validateForm}>SET ALARM</button> </form>輸入元素具有onChange函數(shù),該函數(shù)將其值發(fā)送到狀態(tài)。根據(jù)此值,將顯示驗(yàn)證信號(hào)。(我的意思是如果條件返回 false,紅色邊框會(huì)出現(xiàn),或者輸入警告)const [validate,setValidate] = useState({ message:'', hours:'', minutes:''})function updateHours(e){ let value = e.target.value; let hours = document.getElementById('hours'); let errHours = document.getElementById('errHours'); setValidate(prevState => ({ ...prevState, hours:value }))
1 回答

holdtom
TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超10個(gè)贊
<SetAlarm getInfo={getAlarm} />
在 SetAlarm 組件中
const SetAlarm = ({getInfo}) => {
const validateForm = () => {
getInfo(); // Do whatever you like to do with this
}
return (
<form onSubmit={validateForm}>
<label htmlFor="text">Message</label>
<input type="text" id="text" autoComplete="off" autoFocus="on" />
<button type="submit">SET ALARM</button>
</form>
)
}
添加回答
舉報(bào)
0/150
提交
取消