ReactJS:onClick 函数在单击按钮之前执行

IT技术 reactjs
2021-05-23 06:25:02

该函数SendCred()执行页面正在加载,但我希望在用户单击<button>. 我该怎么办?

 import React,{useState} from "react";

    export default function Signup(props){

      const sendCred=()=>{
        console.log("test")
      };


      return (
        <div className="row container">
          <button onClick={sendCred()}> Activate Laser </button>
        </div>
      );

    };
4个回答

sendCred当您的功能组件的结果被评估和返回时,函数被直接调用:

{/* The sendCred() function is being evaluated during render, and the 
    result of sendCred is being passed to the onClick prop */
<button onClick={sendCred()}> Activate Laser </button>

要实现所需的行为,请考虑将传递给的值指定onClick为包装调用的回调函数sendCred()(即如下所示的箭头函数)。通过这样做,箭头函数将被传递给onClick,当用户单击调用时onClick,将调用提供的箭头函数,这将导致sendCred()调用:

export default function Signup(props){

  const sendCred=()=>{
    console.log("test")
  };

  return (
    <div className="row container">
      {/* Wrap sendCred() with an arrow function, and pass the arrow
          function to onClick as the callback to be invoked for user 
          click events on button */}
      <button onClick={ () => sendCred() }> Activate Laser </button>
    </div>
  );
};

或者,您也可以sendCred直接函数传递给onClick- 这里的关键是确保您不包含括号对(正如您目前所做的那样),因为这样做会导致sendCred在渲染期间被调用:

{ /* Omit the () after sendCred */ }  
<button onClick={ sendCred }> Activate Laser </button>

您只是不应该调用该函数,只需将其直接传递给onClick侦听器

 import React,{useState} from "react";

    export default function Signup(props){

      const sendCred=()=>{
        console.log("test")
      };


      return (
        <div className="row container">
          <button onClick={sendCred}> Activate Laser </button>
        </div>
      );

    };

它也可以用useCallback钩子功能记忆文档

import React,{useState} from "react";

   export default function Signup(props){

     const sendCred = useCallback(() => {
       console.log("test")
     });


     return (
       <div className="row container">
         <button onClick={sendCred}> Activate Laser </button>
       </div>
     );

   };

:)

这发生在我身上,因为我试图将一个props/参数传递给我的 onClick 函数。Dacre Denny对这个问题回答的第一部分让我明白了这一点。

我这样做的原因可能是此问题/堆栈结果的常见原因。

我需要访问无法通过 documentQuerySelector 访问的不同组件中的 dom 元素,因此我试图将来自 useRef 挂钩的 ref 传递到组件中,然后通过 onClick 函数对其进行操作。该函数在加载时执行,而不是在 onClick 上执行。我最终用来处理这个问题的模式如下。

/** Parent Component has access to props or ref and onClick Function **/

import { useRef } from 'react';
const formRef = useRef(); // ref has dom elements need accessing

const onClickFunction=()=>{
var inputs = formRef.current.querySelectorAll('input')
 /* Act on ref or props here via onclick function */
 };
 return(
 <ComponentWithPropsForOnClick formRef={formRef} />
 <ComponentNeedingOnClick onClickFunction={onClickFunction}/>
 )

/** Child component calling function with props or ref**/

export const SSDIBelow = ({ onClickFunction}) =>{

  <button onClick={onClickFunction}>
}

您正在通过使用“sendCred()”在 onClick 内部调用它来执行函数 sendCred。该事件侦听器接收一个函数,因此您应该单独分配 sendCred。

像这样:

 return (
   <div className="row container">
     <button onClick={sendCred}>Activate Laser</button>
   </div>
 );

对于该功能,您应该知道您将收到可能对您有用的事件。

 const sendCred = useCallback((event) => {
   console.log('This is the click event:', event);
   console.log("test");
 });

当 onClick 接收到一个函数时,您可以使用 clousures 来利用您想要与事件一起发送的一些值。

代码如下所示:

   import React, {useState} from "react";

   export default function Signup(props) {

     const sendCred = useCallback((value) => (event) => {
       console.log("I have a value:", value);
       console.log("I have an event:", event);
     });

     return (
       <div className="row container">
         <button onClick={sendCred('Laser')}>Activate Laser</button>
         <button onClick={sendCred('Engine')}>Activate Engine</button>
       </div>
     );
   };

这是有效的,因为您返回一个具有可供使用的值的函数,并且当单击按钮时,第二个函数以事件作为参数执行。

希望能帮助到你!;)