【问题标题】:Cannot perform prop function onClick when usnig stateless functions使用无状态函数时无法执行prop函数onClick
【发布时间】:2020-09-17 06:40:10
【问题描述】:

我似乎无法让我的模态按钮运行我传递给它的功能。

我错过了什么吗?

Dashboard.js

const Dashboard = () => {

    let show = false;

    const showModal = () => {
        console.log('showing modal');
    };

    const hideModal = () => {
        console.log('closing modal');
    };

    return (
        <div>
            <h1>This is the dashboard</h1>
            <button type="button" onClick={showModal}>Open</button>
            <Modal handleClose={hideModal} show={show}/>
        </div>
    )
};

export default Dashboard;

Modal.js

const Modal = (handleClose, show, children) => {
    const showHideClass = show ? 'show-modal' : 'hide-modal';

    return (
        <div className={showHideClass}>
            <h1>This is my modal!</h1>
            <p>{children}</p>
            <button onClick={handleClose}>Close</button>
        </div>
    );
};

export default Modal;

我收到了警告:Expected 'onClick' listener to be a function, instead got a value of 'object' type.,所以我将 modal.js 中的 onClick 更改为 () =&gt; handleClose,这消除了警告,但是当我单击按钮时没有任何反应...

【问题讨论】:

  • 功能组件只需要 one 参数:props。您将其分解为几个变量,但它仍然是一个对象。 @noahCallaway 是正确的。您看到的结果是 handleClose 实际上是自第一个参数以来的整个 props 对象。

标签: javascript reactjs functional-programming stateless


【解决方案1】:

解决方案

你遇到的问题是你没有解构传入的 props 对象。

const Modal = (handleClose, show, children) => {

应该在参数周围放置花括号

const Modal = ({handleClose, show, children}) => {

简要说明

传递给功能组件的道具是单个对象,其键对应于传入对象的名称。对象的形状是:

{
   handleClose: [function],
   show: true,
   children: ...
}

要获取道具,您可以使用单个参数(惯用名为 props),然后从该对象访问值:

const Hello = (props) => {
   console.log(props.message);
}

或者您可以使用解构赋值 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) 来提取函数参数中的道具:

const Hello = ({message}) => {
   console.log(message);
}

【讨论】:

  • 啊,是的,忘记解构了!也解决了我的className 问题。我现在唯一不能开始工作的是模态的显示/隐藏。我一定做错了什么:-/
  • show 被硬编码为false。使用 useState 并将其设置在您的处理程序中。
  • 这可能与您的show-modal、hide-modal css 有关。除非您有理由希望模态在不可见时位于 DOM 中,否则您也可以不渲染模态。例如if (!show) { 返回空值; }
  • @BrianThompson - 谢谢!我刚刚开始掌握 React 的函数式方法,所以可能会有更多问题出现。
  • @NoahCallaway - 是的 - 我正在学习教程:-P
猜你喜欢
  • 1970-01-01
  • 2020-06-24
  • 2016-07-25
  • 2013-10-19
  • 2018-06-29
  • 1970-01-01
  • 2021-02-07
  • 1970-01-01
相关资源
最近更新 更多