简体   繁体   English

可点击的div充当按钮功能react js

[英]Clickable div acting as a button function react js

I have a button function inside the component 'CZButton', the button is used in "personlist" for a pop up, I am trying to make the div card inside of either 'personlist' or 'person' clickable so that instead of clicking the button, the div would be clicked and shows the drawer pop up. 我在组件“ CZButton”内部有一个按钮功能,该按钮用于“个人列表”中的弹出窗口,我试图使“个人列表”或“个人”内部的div卡都可单击,以便代替单击按钮,将单击div并显示弹出的抽屉。

I tried adding onclick inside divs and but it did not seem to reach the drawer function. 我尝试在div内添加onclick,但它似乎没有达到抽屉功能。 here is a sandbox snippet, would appreciate the help. 这是一个沙盒摘要,不胜感激。

https://codesandbox.io/s/l9mrzz8nvz?fontsize=14&moduleview=1 https://codesandbox.io/s/l9mrzz8nvz?fontsize=14&moduleview=1

You can add an onClick listener in React just by writing something like: 您可以在React中添加onClick侦听器,只需编写类似以下内容的代码:

// omitting the rest of the render function for brevity
return (
    <div className="row" onClick={e => console.log("Clicked")}></div>
);

Just be careful with the HTML semantics. 请注意HTML语义。 Although it is possible, I wouldn't really recommend adding onClick events to a div . 虽然有可能,但我不建议您将div添加onClick事件。 There are good resources online about HTML5 standards and what you should adhere too. 在线上有很多有关HTML5标准以及您应该遵循的标准的资源。

Live Demo: https://n329k226om.codesandbox.io/ 现场演示: https : //n329k226om.codesandbox.io/ 单击Div之前 单击Div后

App.js App.js

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component {
  constructor() {
    super();

    this.test = this.test.bind(this);
  }

  test() {
    alert("function executed on clicking div");
  }

  render() {
    return (
      <div>
        <div
          onClick={() => this.test()}
          className="interactivediv fa fa-window-close"
        >
          div
        </div>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

styles.css styles.css的

.App {
  font-family: sans-serif;
  text-align: center;
}

.interactivediv {
  height: 150px;
  width: 150px;
  background: rgb(68, 196, 196);
  cursor: pointer;
   border: 1px solid grey;
}

.interactivediv:active {
  border: 2px solid black;
}

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

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