首页 > 解决方案 > 如何检查“Enter”键的输入

问题描述

我正在开发一个稍微复杂的组件,它基本上允许用户输入输入,然后触发对该产品的搜索(外部 API),但是当前的问题是使用“Enter”键会导致不同的行为我想同步“查找”按钮和“输入”的行为。但在此之前,我在确定应该在哪里进行检查时遇到了一些麻烦,这是我的 React 组件:

export type CcceHook = {
  allowForClassification: boolean,
  classifyInProgress: boolean,
  dataProfileId: string,
  embedID: string,
  handleCancelClassify: () => void,
  handleClassify: (event?: SyntheticEvent<any>) => void,
  handleCloseModal: () => void,
  handleShowModal: () => void,
  isDebugMode: boolean,
  resultCode: string | null,
  shouldShowModal: boolean,
};


// returns Ccce input fields based on the object form model - used in context provider
const getCcceValues = (object?: FormObjectModel | null) => {
  const ccceInput: $Shape<CcceInput> = {};

  //WHERE I THINK THE CHECK SHOULD GO (`ccceInput` is an object, with the `ccce.product` containing the users typed entry)

  if (!object) {
    return {};
  }

  // ccce input values
  const ccceValues = object.attributeCollection.questions.reduce(
    (acc, attribute) => {
      const fieldEntry = ccceBeInformedFieldMap.get(attribute.key);

      if (fieldEntry) {
        acc[fieldEntry] = attribute.value;
      }

      return acc;
    },
    ccceInput
  );

  //check for null or empty string and if so hide "find goods button"
  const productValueWithoutSpaces =
    ccceValues.product && ccceValues.product.replace(/\s+/g, "");

  const canClassify =
    Object.values(ccceValues).every(Boolean) &&
    Boolean(productValueWithoutSpaces);

  return { canClassify, ccceValues };
};

export const useCcceEmbed = (
  ccceResultAttribute: AttributeType,
  onChange: Function
): CcceHook => {
  const { object, form } = useFormObjectContext();
  const [resultCode, setResultCode] = useState<string | null>(null);

  const { canClassify, ccceValues } = getCcceValues(object);

  const { handleSubmit } = useFormSubmit();

  // data profile id is the 'api key' for 3ce
  const dataProfileId = useSelector(
    (state) => state.preferences[DATA_PROFILE_ID]
  );

  // data profile id is the 'api key' for 3ce
  const isDebugMode = useSelector((state) => {
    const value = state.preferences[CCCE_DEBUG_MODE_PREFERENCE];
    try {
      return JSON.parse(value);
    } catch (error) {
      throw new Error(
        `3CE configuration error - non-boolean value for ${CCCE_DEBUG_MODE_PREFERENCE}: ${value}`
      );
    }
  });

  const [showModal, setShowModal] = useState<boolean>(false);

  const handleCloseModal = useCallback(() => setShowModal(false), []);
  const handleShowModal = useCallback(() => setShowModal(true), []);

  // state value to keep track of a current active classification
  const [classifyInProgress, setClassifyInProgress] = useState<boolean>(false);

  // handle results from 3ce
  const handleResult = useCallback(
    (result) => {
      if (result?.hsCode) {
        onChange(ccceResultAttribute, result.hsCode);

        setResultCode(result.hsCode);
        setClassifyInProgress(false);

        handleSubmit(form);
      }
    },
    [ccceResultAttribute, form, handleSubmit, onChange]
  );

  const handleCancelClassify = useCallback(() => {
    setClassifyInProgress(false);
    handleCloseModal();
  }, [handleCloseModal]);

  // handle 3ce classify (https://github.com/3CETechnologies/embed)
  const handleClassify = useCallback(
    (event?: SyntheticEvent<any>) => {
      if (event) {
        event.preventDefault();
      }

      if (classifyInProgress || !canClassify) {
        return;
      }

      const ccce = window.ccce;

      if (!ccceValues || !ccce) {
        throw new Error("Unable to classify - no values or not initialised");
      }

      setClassifyInProgress(true);

      const classificationParameters = {
        ...ccceValues,
        ...DEFAULT_EMBED_PROPS,
      };

      ccce.classify(
        classificationParameters,
        handleResult,
        handleCancelClassify
      );
    },
    [
      classifyInProgress,
      canClassify,
      ccceValues,
      handleResult,
      handleCancelClassify,
    ]
  );

  return {
    allowForClassification: canClassify && !classifyInProgress,
    classifyInProgress,
    dataProfileId,
    embedID: EMBED_ID,
    handleCancelClassify,
    handleClassify,
    handleCloseModal,
    handleShowModal,
    isDebugMode,
    resultCode,
    shouldShowModal: showModal,
  };
};

我已经添加了一条关于我认为应该在哪里处理此逻辑的评论(搜索“//我认为的地方..”) - 但是,我不确定如何从了解用户输入的值到检查输入按,我很高兴能够控制台记录用户的按键,我应该能够从那里绑定逻辑,任何建议都会非常有帮助。

蒂亚!

标签: javascriptreactjskeypress

解决方案


推荐阅读