如何将“onClick”函数传递给 React 中的子组件

时间:2021-01-21 09:38:53

标签: javascript reactjs

我创建了一个非常通用的 Modal,它可以获得不同的页眉、正文和页脚,但也可以为它们的 Reactstrap 组件提供不同的参数(我使用 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>);
    }
}

所以我这样称呼这个类:

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

现在我知道这个方法有效,因为我已经用 className 试过了,例如:

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

我还希望能够传递 onClick 函数 - 但不仅仅是函数(如我们在 this question 中看到的),而是整个:onClick=foo()

我在理解如何将 onClick 方法放入 json 样式格式时遇到了一些问题,就像我对 className 所做的一样。

我无法为 onClick 内的 const bodyArgs = {...} 编写匿名函数,并将其写为

const bodyArgs = {onClick: {foo}};

提供未定义的 foo。我也不能输入 this.foo,因为它也是一种意外的语法。

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

太好了,在我发布此内容后不久就找到了解决方案。

只是不需要 {} 大括号。

const bodyArgs = {onClick: this.foo};

完成工作。

我想我会把它留在这里以防有人偶然发现这个问题。

答案 1 :(得分:0)

这应该像您解释的那样工作,但如果没有整个示例,我无法完全了解。这是一段有效的代码和一个关于您要执行的操作的代码和框链接。

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