我有这行代码,我觉得很糟糕。
{paymentType === "CASH" && status !== "ACCEPTED" && <OnOffButton type="cash" on={status === "CREATED"?false:true} />}
{paymentType === "CASH" && status === "ACCEPTED" && <OnOffButton onClick={()=> status === "CREATED" ? setActionBox({type: 'CREATED'}) : setActionBox({type: 'ACCEPTED'})} type="cash" on={status === "CREATED"?false:true} />}
可以看到,第一行和第二行之间的条件差异是状态,对于第一个选项,我不想使用onClick。有更好的处理方法吗?
下面是稍微好一点的逻辑重构:
import React from 'react'
const ExampleComponent = () => {
const paymentType = 'CARD';
const status = 'ACCEPTED';
if (paymentType !== 'CASH') {
return null;
}
const isOn = status === 'CREATED';
const isAccepted = status === 'ACCEPTED';
return (
<OnOffButton
type="cash"
on={isOn}
onClick={() => isAccepted && setActionBox({ type: status })}
/>
)
}
export default ExampleComponent