简体   繁体   中英

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

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

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. 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>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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