简体   繁体   English

为什么单击事件不适用于样式化组件?

[英]Why is click event not working on styled component?

I created a styled component, I'm trying to fire event handlers but non is firing.我创建了一个样式化的组件,我正在尝试触发事件处理程序,但没有触发。 How can I handle events in styled components?如何处理样式组件中的事件? Here are different versions of the same functionality that I implemented, non of them is working.这是我实现的相同功能的不同版本,它们都不起作用。

V1 V1

import React, { useState } from 'react'
import styled from 'styled-components'


const SomeDiv = styled.div`
                padding: 16px;
                font-family: sans-serif;
                ...
`
export default function CustomDiv(){

const Div = ({ children, onClick }) => {
        return (
            <SomeDiv onClick={onClick}>{children}</SomeDiv>
        )
    }

return(
       <Div onClick={() => console.log('hi')}><span>Hello</span></Div>
)
}

V2 V2

import React, { useState } from 'react'
import styled from 'styled-components'


const SomeDiv = styled.div`
                padding: 16px;
                font-family: sans-serif;
                ...
`
export default function CustomDiv(){


return(
       <SomeDiv onClick={() => console.log('hi')}><span>Hello</span></SomeDiv>
)
}

V2 works just fine for me.V1 needs some work. V2 对我来说很好用。V1 需要一些工作。 Here is both examples working:这是两个示例:

const SomeDiv = styled.div`
  background: blue;
`;
export default function App() {
  const Div = ({ children, onClick }) => {
    return <SomeDiv onClick={() => onClick("testing")}>{children}</SomeDiv>;
  };
  function test(val) {
    console.log("I am");
    console.log(val);
  }
  return (
    <div className="App">
      <SomeDiv onClick={() => console.log("Hello")}>
        <span>Hello</span>
      </SomeDiv>
      <Div onClick={val => test(val)}>test</Div>
    </div>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM