簡體   English   中英

如何將“onClick”function 傳遞給 React 中的子組件

[英]How to pass the 'onClick' function to child component in React

我創建了一個非常通用的 Modal,它可以獲得不同的 header、正文和頁腳,但也可以為其 Reactstrap 組件獲得不同的 arguments(我正在使用 Reactstrap 創建 Modal,但問題不必特定於解決 Reactstrap 問題)。

我的GenericModal.js代碼如下所示:

class GenericModal extends React.Component{

    render(){
        return(
        <Reactstrap.Modal {...this.props.other} />
            <Reactstrap.ModalHeader {...this.props.headerArgs}>{this.props.header}</Reactstrap.ModalHeader>
            <Reactstrap.ModalBody {...this.props.bodyArgs}>{this.props.body}</Reactstrap.ModalBody>
            <Reactstrap.ModalFooter {...this.props.footerArgs}>{this.props.footer}</Reactstrap.ModalFooter>
        </Reactstrap.Modal>);
    }
}

所以我這樣稱呼這個 class :

<GenericCard {...{other: other, headerArgs: headerArgs, bodyArgs: bodyArgs, footerArgs: footerArgs, 
              cardheader:header, cardbody:body, cardfooter:footer}} />

現在我知道這種方法有效,因為我已經嘗試過使用className ,例如:

const bodyArgs = {className: 'my-5'};

我還希望能夠通過onClick function - 但不僅僅是 function (正如我們在這個問題中看到的那樣),而是整個事情: onClick=foo()

我在理解如何將onClick方法放入 json 樣式格式中時遇到了一些問題,就像我對className所做的那樣。

我不能在const bodyArgs = {...}中為onClick編寫匿名 function ,並將其寫為

const bodyArgs = {onClick: {foo}};

提供未定義的foo 我也不能放this.foo因為它也是一個意外的語法。

有什么想法嗎?

Welp,在我發布此消息后立即找到了解決方案。

只是不需要{}大括號。

const bodyArgs = {onClick: this.foo};

做這項工作。

以為我會把它留在這里,以防有人偶然發現這個問題。

正如您所解釋的那樣,這應該可以工作,但是如果沒有整個示例,我將無法完全知道。 這是一段工作代碼和一個代碼框鏈接,說明您要做的事情。

import React from "react";
import "./styles.css";

class ClickExecutor extends React.Component {
  render() {
    return (
      <div>
        <h4>Click Executor</h4>
        <div>
          <button onClick={() => this.props.bodyArgs.alert1()}>One</button>
          <button onClick={() => this.props.bodyArgs.alert2()}>Two</button>
        </div>
      </div>
    );
  }
}

class GenericModal extends React.Component {
  alert1 = () => {
    alert("Alert 1");
  };

  alert2 = () => {
    alert("Alert 2");
  };

  render() {
    const bodyArgs = {
      alert1: this.alert1,
      alert2: this.alert2
    };

    return (
      <div>
        <h1>Generic Modal</h1>
        <ClickExecutor
          {...{
            bodyArgs: bodyArgs,
            otherProps: "other various properties ..."
          }}
        />
      </div>
    );
  }
}

export default function App() {
  return (
    <div className="App">
      <GenericModal />
    </div>
  );
}

工作演示鏈接: https://codesandbox.io/s/smoosh-frost-rj1vb

暫無
暫無

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

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