在 React-Native 中定义静态 PropType 时“.isRequired”的含义

Isa*_*tte 4 reactjs react-native

static propTypes = {
  // Value to display
  value: PropTypes.string.isRequired,
  // Wheter this values was chosen by user or not
  isChosen: PropTypes.bool.isRequired,
  // Gets called when user choses this value
  onChoose: PropTypes.func.isRequired,
}
Run Code Online (Sandbox Code Playgroud)

为什么在定义上述 PropType 时要添加“.isRequired”?我是一个反应原生初学者

jev*_*lio 6

如果你用 定义 PropType isRequired,当你使用该组件而不传递该 prop 时,React 会警告你。

// -> Warning: onChoose is required but not provided
<Component value={val} isChosen={true} /> 
Run Code Online (Sandbox Code Playgroud)

如果您没有定义它,则该属性被视为可选,并且如果您不传递该属性,则不会显示警告。

// -> No warnings, since the props are not required.
<Component /> 
Run Code Online (Sandbox Code Playgroud)