【问题标题】:Clickable div acting as a button function react js可点击的 div 充当按钮功能 react js
【发布时间】:2019-07-19 14:40:06
【问题描述】:

我在组件“CZButton”中有一个按钮功能,该按钮在“personlist”中用于弹出窗口,我试图使“personlist”或“person”内的 div 卡可点击,以便改为单击按钮,将单击 div 并显示抽屉弹出。

我尝试在 div 中添加 onclick,但似乎没有达到抽屉功能。这是一个沙盒 sn-p,不胜感激。

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

【问题讨论】:

  • Drawer 的代码在按钮组件及其状态中进行编码。您必须将相应的代码移动到 Person 组件并在此处添加 onClick
  • 这能回答你的问题吗? How to use onClick with divs in React.js

标签: javascript html css reactjs web-applications


【解决方案1】:

您可以在 React 中添加一个 onClick 监听器,只需编写如下代码:

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

请注意 HTML 语义。尽管有可能,但我真的不建议将 onClick 事件添加到 div。网上有很多关于 HTML5 标准以及您应该遵守的内容的好资源。

【讨论】:

    【解决方案2】:

    现场演示: https://n329k226om.codesandbox.io/

    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

    .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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-08
      • 1970-01-01
      • 2015-04-13
      • 1970-01-01
      • 2018-03-07
      • 2015-09-15
      • 1970-01-01
      相关资源
      最近更新 更多