Styled 组件上的 onClick 事件处理 (DIV)

onClick event handling on a Styled-component (DIV)

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

这是我构建的伪代码:

<Styled_DIV onClick={() => props.method(props.arg)}>
  <AnotherElement/>
  ...
</Styled_DIV>

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

<div onClick={() => props.method(props.arg)}>
 <Styled_DIV}>
   <AnotherElement/>
   ...
 </Styled_DIV>
</div>

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

提前致谢:)

因为您没有创建将呈现标签的 Styled_DIV 组件

只需添加此代码

const Styled_DIV = styled.div``

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

index.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"));

Wrapper.js:

import styled from "styled-components";

export default styled.button`
  font-size: 1.5em;
  text-align: center;
  color: palevioletred;
`;

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

您还有其他选择,例如 字体样式 https://github.com/typestyle/typestyle, Styletron https://github.com/styletron/styletron 和其他可以与 React 一起使用的。