简体   繁体   English

使用无状态函数时无法执行道具 function onClick

[英]Cannot perform prop function onClick when usnig stateless functions

I can't seem to get my modal button to run the function I have passed into it.我似乎无法让我的模态按钮运行我传递给它的 function。

Am I missing something?我错过了什么吗?

Dashboard.js仪表板.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模态.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;

I had the warning: Expected 'onClick' listener to be a function, instead got a value of 'object' type.我收到警告: Expected 'onClick' listener to be a function, instead got a value of 'object' type. , so I changed the onClick in modal.js to () => handleClose which dismissed the warning, however nothing happened when I clicked the button... ,所以我将onClick中的onClick更改为() => handleClose ,它消除了警告,但是当我单击按钮时没有任何反应......

The Solution解决方案

The issue you're having is you're not destructuring the props object that's passed in.您遇到的问题是您没有破坏传入的道具 object 。

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

should instead put curly braces around the arguments应该在 arguments 周围放置花括号

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

Brief Explanation简要说明

The props passed to a functional component are a single object with keys that correspond to the name of the object passed in. The object's shape would be:传递给功能组件的道具是单个 object,其键对应于传入的 object 的名称。对象的形状将是:

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

To get the props, you can either have a single argument (idiomatically named props ), and then access values from that object:要获取道具,您可以使用单个参数(惯用名为props ),然后从该 object 访问值:

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

Or you can use a destructuring assignment ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment ) to extract the props in the function arguments:或者您可以使用解构分配( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment )来提取 function ZDBC11FB4DABDBDA8 中的道具

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM