如何在使用钩子的功能组件中正确使用React PropTypes?

时间:2019-07-16 10:09:10

标签: reactjs react-hooks react-proptypes

我试图在功能性的React组件中使用PropType,但是添加PropType之后,我得到了Hooks can only be called inside the body of a function component.

我看了看PropType文档,发现了以下内容

const myPropTypes = {
  name: PropTypes.string,
  age: PropTypes.number,
  // ... define your prop validations
};

const props = {
  name: 'hello', // is valid
  age: 'world', // not valid
};

// Let's say your component is called 'MyComponent'

// Works with standalone PropTypes
PropTypes.checkPropTypes(myPropTypes, props, 'age', 'MyComponent');
// This will warn as follows:
// Warning: Failed prop type: Invalid prop `age` of type `string` supplied to
// `MyComponent`, expected `number`.

我可以想象在功能组件中使用它。但这是唯一的方法,还是有更好的方法?

我的代码现在看起来像这样:

const MyComponent = (props) => {
  const { title } = props;
  const [showTitle, setShowTitle] = useState(true);
  return (
    <div>
      <button onClick={()=>setShowTitle(!showTitle)}>toggle title</button>
      {showTitle && <h1>{title}</h1>}
    </div>
  );

MyComponent.propType = {
  title: PropTypes.string
}

MyComponent.defaultProps = {
  title: 'hello'
}

0 个答案:

没有答案