样式组件(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.