繁体   English   中英

Reactjs/Nextjs onClick 事件不适用于外部组件

[英]Reactjs/Nextjs onClick event not working for external component

我有一个主页,上面有一个我创建的按钮组件,可以在我的项目中重用。 我的问题是当我将 onClick 事件添加到我的外部组件时,点击事件不起作用,但是我是否在我的主页中创建相同的按钮,点击事件工作正常

按钮组件

import React from "react";
import styled from "styled-components";

const BigButton = (props): JSX.Element => {
    return <>{props.red ? <BigBtn red={props.red}>{props.val}</BigBtn> : <BigBtn>{props.val}</BigBtn>}</>;
};

export default BigButton;

const BigBtn = styled.button`
    font-style: normal;
    font-weight: 500;
    font-size: 12px;
    line-height: 15px;
    color: #f5f5f5;
    width: 78px;
    height: 30px;
    background: ${(props) => (props.red ? "#BD2129" : "#2e3034")};
    border: ${(props) => (props.red ? "initial" : "1px solid #494b4f")};
    border-radius: 2px;
    display: flex;
    align-items: center;
    justify-content: center;
`;

这适用于主页

<button onClick={buttonClose}>Close</button>

主页上的按钮组件 - 这在主页上不起作用

<BigButton val="Cancel" onClick={handleClose} />

关闭 function

const handleClose = (e) => {
        e.preventDefault();
        props.onClose();
    };

您的组件看起来不正确。 您没有组件内部的buttononClick事件。 你应该这样更新

import React from "react";
import styled from "styled-components";

const BigButton = (props): JSX.Element => {

const handleClick = () => {
            props.onClick()
    }
    return <>{props.red ? 
                    <BigBtn red={props.red}>
              <button onClick={handleClick}>
                  {props.val}
              </button>
            </BigBtn> : 
              <BigBtn>
                <button onClick={handleClick}>
                  {props.val}
                </button>
              </BigBtn>}
           </>
};

export default BigButton;

const BigBtn = styled.button`
    font-style: normal;
    font-weight: 500;
    font-size: 12px;
    line-height: 15px;
    color: #f5f5f5;
    width: 78px;
    height: 30px;
    background: ${(props) => (props.red ? "#BD2129" : "#2e3034")};
    border: ${(props) => (props.red ? "initial" : "1px solid #494b4f")};
    border-radius: 2px;
    display: flex;
    align-items: center;
    justify-content: center;
`;

暂无
暂无

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

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