0

第一次尝试使用useRef所以原谅任何非常明显的错误。我有两个组件(父组件和子组件)-在父组件中,我基本上试图useRef传递handleOnKeyDown给我的子组件(findGoodsBtn)所在的位置,并且基本上在用户输入“Enter”时复制对该按钮的单击。

父组件是新的,我认为一些语法可能有点偏离,子组件已经工作了,所以可能只需要一个小的调整来接受ref- 任何人都可以告诉我哪里可能出错了吗?

家长:

const CommodityCodeLookupAttribute = React.forwardRef<
  Props,
  typeof CcceAttribute
>(
  (
    { attribute: productLookupAttribute, onChange, ...otherProps }: Props,
    ref
  ) => {

    const findGoodsBtnRef = useRef();

    const { object } = useFormObjectContext();

    const ccceAttribute = object.attributeCollection.find(
      isCcceResultAttribute
    );

    if (!ccceAttribute) {
      return null;
    }

    const handleOnKeyDown = (event) => {
      if (event.keyCode === "13") {
        // event.preventDefault();
        console.log("literally anything");
        findGoodsBtnRef.current.click();
        // use the ref that points to the ccce attribute button -> click()
      }
    };

    return (
      <>
        <StringAttributeDefault
          attribute={productLookupAttribute}
          onKeyDown={handleOnKeyDown}
          {...otherProps}
        />

        {/* needs to accept a ref */}
        {/* forwardRef */}
        <CcceAttribute attribute={ccceAttribute} ref={findGoodsBtnRef} />
      </>
    );
  }
);

孩子:

const CcceAttribute = ({
  attribute,
  onChange,
}: {
  ...Props<StringAttributeModel | NumberAttributeModel | MoneyAttributeModel>,
  ...StringAttributeProps,
}) => {
  const {
    allowForClassification,
    classifyInProgress,
    dataProfileId,
    embedID,
    handleCancelClassify,
    handleClassify,
    handleShowModal,
    isDebugMode,
    resultCode,
    shouldShowModal,
    ref,
  } = useCcceEmbed(attribute, onChange);

  const showLookupButton =
    (allowForClassification || classifyInProgress) && !resultCode;

  return (
    <>
      {showLookupButton ? (
        <StyledButtonContainer>
          <StyledLookupButton
            disabled={!allowForClassification || classifyInProgress}
            onClick={handleShowModal}
            buttonStyle="PRIMARY"
            ref={ref}
          >
            Find goods
          </StyledLookupButton>
        </StyledButtonContainer>
      ) : null}
      )}
    </>
  );
};

我应该在控制台中添加我收到错误消息:“警告:无法为函数组件提供参考。访问此参考的尝试将失败。您的意思是使用 React.forwardRef() 吗?” - 之前检查过各种答案,但认为这可能取决于子组件?

4

0 回答 0