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

Dhi*_*uah 3 reactjs

该函数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>
      );

    };
Run Code Online (Sandbox Code Playgroud)

Dac*_*nny 5

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>
Run Code Online (Sandbox Code Playgroud)

为了实现所需的行为,请考虑将onClick传递给的值指定为包装调用的回调函数sendCred()(即如下所示的箭头函数)。通过这样做,箭头函数将被传递到onClick,并且当用户单击 invokes 时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>
  );
};
Run Code Online (Sandbox Code Playgroud)

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

{ /* Omit the () after sendCred */ }  
<button onClick={ sendCred }> Activate Laser </button>
Run Code Online (Sandbox Code Playgroud)