簡體   English   中英

如何將 onclick function 添加到自定義 React 組件?

[英]How do I add a onclick function to a custom React Component?

我是 React 的新手。 我有 3 個按鈕作為組件導入 App.js,如下所示:

import Button from "./Button";

我想將 onClick function 添加到這些組件中:

<div className="buttonsdiv">
        <Button text="+" / onClick = {...}>
//text is a parameter defined in Button.js
        <Button text="RESET" onClick = {...} />
        <Button text="-"onClick = {...} />
      </div>

有沒有辦法做到這一點?

正如@BrianThompson 所說,這完全取決於您的Button組件的實現。 這個想法是將onClick傳遞給渲染的 html 元素,即:

const Button = (props) => {
    return (
        <button onClick={props.onClick}/>
    );
}

如果它是功能組件,請嘗試以下操作:

JavaScript

 const add = (e) => { }
 const sub = (e) => { }
 const reset = (e) => { }

JSX

  <div className="buttonsdiv">
    <Button text="+" onclick={add} />
    <Button text="RESET" onclick={reset} />
    <Button text="-" onclick={sub} />
  </div>

如果它是沒有 state 的組件,則將函數傳遞給組件,如下所示:

const component = (props) => {
    return { 
      <div className="buttonsdiv">
        <Button text="+" onclick={props.add} />
        <Button text="RESET" onclick={props.reset} />
        <Button text="-" onclick={props.sub} />
      </div>
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM