样式组件(DIV)上的onClick事件处理 [英] onClick event handling on a Styled-component (DIV)

查看:208
本文介绍了样式组件(DIV)上的onClick事件处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to handle an onClick event on a DIV (in REACT JS) which is a styled-component actually. But this not works at all.

这是我构建的伪代码:

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

我可以正常运行的解决方法:

My workaround which works properly:

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

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

So, my question is: what's the official / best way to handle an onClick event on a styled-component div without wrapper div?

先谢谢您了:)

推荐答案

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

You can attach the event handlers directly without wrapper 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:

Wrapper.js:

import styled from "styled-components";

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

代码链接: 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一起使用的.

You also have other options like typestyle https://github.com/typestyle/typestyle, Styletron https://github.com/styletron/styletron and others as well which can be used with react.

这篇关于样式组件(DIV)上的onClick事件处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆