如何在不同的组件中调用函数

我在调用函数时遇到问题。这个函数在主App.js文件中,它作为 prop 传递给不同的组件。如果表单验证返回 true 但我的代码不起作用,我需要调用此函数。


App.js 中的函数


  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} />

在这个组件中,我有一些小表格,其中有一些验证。为了更好地理解,我还将向您展示表单和这些功能。


形式


<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函数,该函数将其值发送到状态。根据此值,将显示验证信号。(我的意思是如果条件返回 false,红色边框会出现,或者输入警告)


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

    }))



慕标琳琳
浏览 135回答 1
1回答

holdtom

<SetAlarm getInfo={getAlarm} />在 SetAlarm 组件中const SetAlarm = ({getInfo}) => {&nbsp; const validateForm = () => {&nbsp; &nbsp; &nbsp;getInfo(); // Do whatever you like to do with this&nbsp;&nbsp; }&nbsp; return (&nbsp; &nbsp; &nbsp;<form onSubmit={validateForm}>&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; <label htmlFor="text">Message</label>&nbsp; &nbsp; &nbsp; &nbsp; <input type="text" id="text" autoComplete="off" autoFocus="on" />&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; <button type="submit">SET ALARM</button>&nbsp; &nbsp; &nbsp;</form>&nbsp; )}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript