javascript - 如何向 React js 按钮添加多个功能?
问题描述
我想像startClick
在 NextButton 中一样添加到 BackButton。换句话说,当点击 BackButton 时,startClick
函数应该首先工作,然后dispatch (giveForm2PreviousStep (props.currentStep, props.goToStep))
方法应该按顺序工作。我怎样才能做到这一点?
问题 JS
const Question = props => {
const dispatch = useDispatch()
const loading = useSelector(state => state.app.isLoading)
const error = useSelector(state => state.app.error)
const reduxF2 = useSelector(state => state.app.forms.f2)
const [input, setInput] = useState({
value: reduxF2.PastReceivables.value,
valid: true,
})
const changeSelected = val => {
setInput({ ...input, value: val })
}
useEffect(() => {
setInput({ ...input, value: reduxF2.PastReceivables.value })
}, [reduxF2.PastReceivables.value])
useEffect(() => {
if (reduxF2.bulkSaved && props.currentStep === 2) {
dispatch(giveForm2NextStep(props.currentStep, props.goToStep))
dispatch(resetForm2SavedStatus())
}
}, [reduxF2.bulkSaved])
const startClick = e => {
if (input.value === null || input.value === '') {
setInput({ ...input, valid: false })
} else {
setInput({ ...input, valid: true })
const questions = getPastReceivablesArray('PastReceivables', input.value, reduxF2)
if (questions.length == 0) {
dispatch(giveForm2NextStep(props.currentStep, props.goToStep))
} else {
dispatch(updateForm2(questions))
}
}
}
return (
<>
<MyProgressBar now='8' />
<Question>Question here</Question>
<QuestionForm>
<NumericInput
valid={input.valid}
onChange={changeSelected}
value={input.value}
/>
</QuestionForm>
<div className='d-flex justify-content-between'>
<BackButton onClick={() => dispatch(giveForm2PreviousStep(props.currentStep, props.goToStep))} />
<NextButton onClick={startClick} loading={loading} />
</div>
<Warning error={error} />
</>
)
}
后退按钮 JS
const BackButton = ({ text = 'Back', onClick = null, loading = false, width = '7.5rem' }) => {
return (
<Button
variant='secondary'
className='back-button'
onClick={onClick}
disabled={loading}
style={{width}}
>
<MySpinner loading={loading} />
{!loading && <>{text}</>}
</Button>
)
}
解决方案
您可以在 onClick 事件中调用多个函数,如下所示
<BackButton
onClick={(e) => {
startClick(e);
dispatch(giveForm2PreviousStep(props.currentStep, props.goToStep))
}}
/>
推荐阅读
- r - 编辑日期格式并使用日期对数据框进行排序
- sql-server - SQL 报表生成器:添加
下拉选项 - tags - 黄瓜标签 - 仅执行具有 2 个特定标签的功能
- javascript - 将带有句号的单词拆分为单独的字符范围,包括句号
- tomcat - 阻止tomcat webapp上的特定瓮
- uwp-xaml - 如何在 UWP 的滚动查看器中启用水平滚动和禁用垂直滚动?
- javascript - React:使用扩展运算符使用表单数据 onChange 更新状态
- python - 为什么“组成”系列不会导致“输入”系列的索引?
- javascript - 在 webpack 设置中为 vuejs 保存一次性使用数据的位置
- c# - UWP 应用程序在发布时无法启动,“未找到依赖的 DLL”。在调试中工作,没有附加信息