简体   繁体   中英

React onclick setState not working with arrow function

I have a component. I want to calculate some numbers here. When click the button it's not working with onClick={() => setEarned(calculateEarned)} . But when I change it like onClick={setEarned(calculateEarned)} it works but one time and when the page loaded. So I'm stack. Where is the problem I couldn't find.

import { Button, PrimaryButton } from "../../components/Button/Button"

export const CryptoCalculator = () => {
    const [earned, setEarned] = useState(0)

    function calculateEarned() {
        console.log('hit')
        return 1
    }

    return (
        <Container>
            <PrimaryButton
                title="Calculate"
                onClick={() => setEarned(calculateEarned)}
            ></PrimaryButton>

            <Earned>{earned}</Earned>
        </Container>
    )
}

EDIT: Problem solved. The problem is with the PrimaryButton component. I tried with button and then function worked. Here is the Button component:

import styled from "styled-components"

const Btn = styled.button`
    /*some css codes*/
`

const PrimaryBtn = styled(Btn)`
    /*some special css codes for primary button*/
`

export const Button = ({ title }) => {
    return <Btn>{title}</Btn>
}

export const PrimaryButton = ({ title }) => {
    return <PrimaryBtn>{title}</PrimaryBtn>
}

You need to call your function correct way. setEarned(calculateEarned()) instead of setEarned(calculateEarned)

Example :

export const CryptoCalculator = () => {
    const [earned, setEarned] = useState(0)

    function calculateEarned() {
        console.log('hit')
        return 1
    }

    return (
        <Container>
            <PrimaryButton
                title="Calculate"
                onClick={() => setEarned(calculateEarned())}
            ></PrimaryButton>

            <Earned>{earned}</Earned>
        </Container>
    )
}

I've added onClick prop to Button component and then it started to act like a button. So, problem solved!

export const Button = ({ title, onClick }) => {
    return <Btn onClick={onClick}>{title}</Btn>
}

export const PrimaryButton = ({ title, onClick }) => {
    return <PrimaryBtn onClick={onClick}>{title}</PrimaryBtn>
}

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