簡體   English   中英

PropTypes.defaultProps 用於無狀態組件中的 function

[英]PropTypes.defaultProps for a function in a stateless component

問題

我有一個功能組件,它可能會接收一個可選的 function 作為道具。 我正在使用 propTypes 來定義不成比例的道具的默認值。 有什么方法可以將 function(在 defaultProps 中)的默認值定義為特定組件的 function?

代碼

export default function Cropper(props) {
   ...
   const handleOnCrop = () => { // <-------
      // Stuff
   }
   ...

   const handleConfirm = () => {
      if (!isCropping) {
          setIsCropping(true);
          cropPhoto().then((croppedPhoto) => {
            onCrop(croppedPhoto); // <----------------
            InteractionManager.runAfterInteractions(() => {
              setIsCropping(false);
            });
          });
       }
    };
}

道具類型

Cropper.propTypes = {
  navigation: PropTypes.object.isRequired,
  photo: PropTypes.object.isRequired,
  onCrop: PropTypes.func.isRequired,
};

Cropper.defaultProps = {
  onCrop: // This has to be the functional component function "handleOnCrop" <--------
}; 

解決方法

Cropper.defaultProps = {
  onCrop: (photo, navigation) => { // <---------- Passing the navigation object from the component is not really good
    navigation.navigate("PostCreator", {
      photo,
    });
  },
};

我認為這不是處理此問題的最佳方法,但對我有用。 無論如何,我需要將其更改為有狀態組件中的內容。

如果我理解正確,您需要表達一種類型,它不是 PropType 的可用導出之一(object、func、arrayOf 等)。 如果是這種情況,我看到了一些解決方案,這些解決方案因您需要 PropTypes 的具體程度而異。

PropTypes.instanceOf

https://github.com/facebook/prop-types#usage

查看 URL 中的錨定部分。在示例中,您可以找到以下代碼段:

  // You can also declare that a prop is an instance of a class. This uses
  // JS's instanceof operator.
  optionalMessage: PropTypes.instanceOf(Message),

如果你有一個有效的出口/進口,我認為你可以在你的情況下重用它

 the functional component function "handleOnCrop"

正如你提到的。

這是迄今為止我能想到的最具體的道具類型。 讓我們看看其他一些解決方案。

如果您可以更廣泛地概括道具,您可以求助於

PropTypes.node

從上面提到的url中描述如下:

// Anything that can be rendered: numbers, strings, elements or an array
  // (or fragment) containing these types.
  optionalNode: PropTypes.node,

我最不喜歡的解決方案,

PropTypes.any

我認為這是不言自明的,而不是你正在尋找的東西,所以你應該把它作為最后的手段。

這是根據我對你問題的理解做出的回答,歡迎留言進一步解釋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM