首页 > 解决方案 > 如何向 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>
  )
}

标签: javascriptreactjsreact-hooks

解决方案


您可以在 onClick 事件中调用多个函数,如下所示

<BackButton 
    onClick={(e) => {
        startClick(e);
        dispatch(giveForm2PreviousStep(props.currentStep, props.goToStep))
    }} 
/>

推荐阅读