reactjs 本机React,设置状态更改检查值

enyaitl3  于 2023-01-17  发布在  React
关注(0)|答案(1)|浏览(110)

我有一个搜索输入,我想在用户与字段交互时触发事件trackButtonClickEventAction(buttonClick.MY_VEHICLES_ADD_VEHICLE_REG_INPUT)。但是,当用户输入数字时触发事件,我想在输入数字且输入失去焦点时触发事件,有什么想法吗?

const onChange = (args) => {
    const inputValue = args[0].nativeEvent.text;
    if (state.reg.length === 0) {
      console.log(buttonClick.MY_VEHICLES_ADD_VEHICLE_REG_INPUT);
      trackButtonClickEventAction(
        buttonClick.MY_VEHICLES_ADD_VEHICLE_REG_INPUT,
      );
    }

    if (inputValue) {
      console.log(buttonClick.MY_VEHICLES_ADD_VEHICLE_REG);
      trackButtonClickEventAction(buttonClick.MY_VEHICLES_ADD_VEHICLE_REG);
      setState((prevState) => ({
        ...prevState,
        reg: inputValue,
        disableButton: false,
      }));
    } else {
      setState((prevState) => ({
        ...prevState,
        reg: '',
        disableButton: true,
      }));
    }
    return inputValue;
  };

控制器:

<Controller
    as={<InputField />}
    control={control}
    label="Number plate"
    name="reg"
    value={state.reg}
    defaultValue={state.reg}
    onChange={onChange}
    rules={{ required: true }}
    errorMessage={getError(errors.reg)}
    resetOnEmpty
    rightIcon={
      <TouchableOpacity
        activeOpacity={0.8}
        onPress={() => {
          handleSubmit(onSubmit)();
          console.log(buttonClick.MY_VEHICLE_ADD_VEHICLE_INPUT_BUTTON);
          trackButtonClickEventAction(
            buttonClick.MY_VEHICLE_ADD_VEHICLE_INPUT_BUTTON,
          );
        }}
        style={forms.rightIcon}>
        <Icon
          name="search"
          size={32}
          color="#707070"
          style={forms.searchStyle}
        />
      </TouchableOpacity>
    }
  />
e1xvtsh3

e1xvtsh31#

您可以使用onBlur属性。当input失去焦点时,将调用onBlur

<input
  onBlur={(e) => {
    console.log('input lost focus', e);
  }}
  onFocus={(e) => {
    console.log('input gained focus', e);
  }}
/>

相关问题