我有一个组件。我想在这里计算一些数字。当点击按钮,它不与onClick={() => setEarned(calculateEarned)}
工作。但是当我像onClick={setEarned(calculateEarned)}
一样改变它时,它只工作一次,当页面加载时。所以我是stack。我找不到的问题在哪里?
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>
)
}
编辑:问题解决。问题是与PrimaryButton
组件。我尝试了button
,然后功能工作。下面是Button
组件:
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>
}
您需要以正确的方式调用您的函数。setEarned(calculateEarned())
代替setEarned(calculateEarned)
的例子:
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>
)
}
我已经将onClick
prop添加到Button
组件,然后它开始像按钮一样起作用。所以,问题解决了!
export const Button = ({ title, onClick }) => {
return <Btn onClick={onClick}>{title}</Btn>
}
export const PrimaryButton = ({ title, onClick }) => {
return <PrimaryBtn onClick={onClick}>{title}</PrimaryBtn>
}