React - 渲染库的父组件的propTypes?

时间:2018-02-17 17:28:05

标签: reactjs react-proptypes

我有疑问: 我正在使用react-dates datepicker库,我想知道:我不能定义propTypes(我在哪里渲染datepicker我不使用任何道具)但在这种情况下,什么被认为是好的反应练习?当我不使用库但是自己编写我的hild组件时,我会自己定义孩子内部的proptypes等等但是当我使用库时“他们的代码”不容易查找的时候是什么?我的情况(请参阅下面的代码),例如强制性的,属性“startDate”是一个对象。当我以某种方式定义它洞察我的组件以便其他人可以轻松地看到预期的内容时会不会很好? 我只是想编写更好的代码,并想知道在这种情况下最好的代码。谢谢!

export default class App extends React.Component {
   render(){
      return (
         <DayPickerRangeController
            startDate={this.state.startDate} // momentPropTypes.momentObj or null,
            endDate={this.state.endDate} // momentPropTypes.momentObj or null,
            onDatesChange={({ startDate, endDate }) => this.setState({ startDate, endDate })} // PropTypes.func.isRequired,
            focusedInput={this.state.focusedInput} // PropTypes.oneOf([START_DATE, END_DATE]) or null,
            onFocusChange={focusedInput => this.setState({ focusedInput })} // PropTypes.func.isRequired,
         />
      )
   }
}

1 个答案:

答案 0 :(得分:0)

您可以定义一个包装器功能组件,它将所有道具委托给子组件并将prop类型与其关联。

export const DayPickerWrapper = (props) => <DayPickerRangeController {...props}/>;

DayPickerWrapper.propTypes = { /* Add additional validations here */ }

在应用程序的其余部分中,您可以使用DayPickerWrapper而不是DayPicker。

如果你真的想避免包装器的开销,你也可以直接更改组件类的propTypes:

DayPickerRangeController.propTypes = {
  ...DayPickerRangeController.propTypes,
  // Add custom validations here
}

在渲染中使用它之前导入一次。

相关问题