如何向React js按钮添加多个功能?

时间:2020-05-27 06:58:17

标签: javascript reactjs react-hooks

我想像在NextButton中一样向BackButton添加startClick。换句话说,单击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} />
    </>
  )
}

BackButton 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>
  )
}

2 个答案:

答案 0 :(得分:4)

您可以在如下所示的onClick事件中调用多个功能

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

答案 1 :(得分:1)

您可以在onclick中调用多个功能,也可以将回调发送给startclick。 因此,回调将在startclick之后执行。 轻松提供onClick本身的所有功能。