簡體   English   中英

PropType 可選的反應組件

[英]PropType optional to react component

我有以下通用組件

import PropTypes from 'prop-types';
import Input from '../component/Input'; //internal component 

const CustomInput = props => {
  const { label, updateInputField } = props;
  return (
    <Input
      label={label}
      changeField={updateInputField}
  )
}

CustomInput.propTypes = {
  label: PropTypes.string,
  updateInputField: PropTypes.func
}

export default CustomInput;

現在我在以下幾個地方使用這些組件

<CustomInput 
  label="401Balance"
  updateInputField={inputFieldHandler}
/>

所以這個工作.. 但有些地方我沒有使用 updateInputField 作為道具。 例如

<CustomInput 
  label="savingsBalance"
/>

我如何不通過道具並確保它不會失敗。 有人可以建議。

如果沒有傳遞任何函數,您可以設置一個默認值來保護案例:

const { label, updateInputField = () => {} } = props;

或者(可能是更好的方法) - 創建一個單獨的函數並添加一個簡單的條件:

const CustomInput = props => {
  const { label, updateInputField } = props;

  const fn = () => {
     if (updateInputField) {
        updateInputField();
     }
  };

  return (
     <Input
        label={label}
        changeField={fn}
     />
  );
}

暫無
暫無

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

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