样式组件 (DIV) 上的 onClick 事件处理

Cre*_*key 5 html onclick event-handling reactjs styled-components

我想处理 DIV(在 REACT JS 中)上的 onClick 事件,它实际上是一个样式组件。但这根本不起作用。

这是我的构建的伪代码:

<Styled_DIV onClick={() => props.method(props.arg)}>
  <AnotherElement/>
  ...
</Styled_DIV>
Run Code Online (Sandbox Code Playgroud)

我的解决方法可以正常工作:

<div onClick={() => props.method(props.arg)}>
 <Styled_DIV}>
   <AnotherElement/>
   ...
 </Styled_DIV>
</div>
Run Code Online (Sandbox Code Playgroud)

所以,我的问题是:在没有包装器 div 的情况下处理样式组件 div 上的 onClick 事件的官方/最佳方法是什么?

提前致谢 :)

小智 11

您可以直接附加事件处理程序,无需包装 div。

索引.js

import React from "react";
import { render } from "react-dom";
import Wrapper from "./Wrapper";

const App = () => <Wrapper onClick={() => alert("Hello")}>Hello</Wrapper>;

render(<App />, document.getElementById("root"));
Run Code Online (Sandbox Code Playgroud)

包装器.js:

import styled from "styled-components";

export default styled.button`
  font-size: 1.5em;
  text-align: center;
  color: palevioletred;
`;
Run Code Online (Sandbox Code Playgroud)

代码链接:https://codesandbox.io/s/styled-components-d731y ?fontsize=14&hidenavigation=1&theme=dark

您还可以使用其他选项,例如 typestyle https://github.com/typestyle/typestyle、 Styletron https://github.com/styletron/styletron等,这些选项也可以与 React 一起使用。