[英]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 事件的官方/最佳方法是什么?
提前致谢 :)
您可以直接附加事件处理程序而无需包装 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"));
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 一起使用。
因为您没有创建将呈现标签的 Styled_DIV 组件
只需添加此代码
const Styled_DIV = styled.div``
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.