我可以从其他组件的默认道具分配默认道具吗

Can I assign default props from other component's default props

我有两个组件,这两个组件共享相同的道具。

我可以通过直接将它们设置为其他组件的默认道具来分配默认道具和道具类型吗

例如

static propTypes = CookiePreferenceButton.propTypes;

static defaultProps = CookiePreferenceButton.defaultProps;

其中 CookiePreferenceButton 是无状态组件。

const CookiePreferenceButton = ({buttonText, buttonStyle, className}) => (
  <button className={styles[className]} style={buttonStyle}>
    {buttonText}
  </button>
);

CookiePreferenceButton.propTypes = {
  buttonText: PropTypes.string,
  className: PropTypes.string,
  buttonStyle: PropTypes.shape({
    background: PropTypes.string,
    borderColor: PropTypes.string,
    color: PropTypes.string,
  }),
};

CookiePreferenceButton.defaultProps = {
  buttonText: 'Manage Cookie Preference',
  className: 'cookie-preference-preview-button',
  buttonStyle: {
    background: '#209ce9',
    borderColor: '#209ce9',
    color: '#fff',
  },
};

export default CookiePreferenceButton;

与其使用来自其他组件的道具类型,不如在单独的文件中定义道具类型,并在两个组件中使用它们:

export const CookieButton = {
  // ... your prop types
}

// import CookieButton and use it
static defaultProps = CookieButton
// another component
static propTypes = CookieButton;

是的,您可以在组件之间共享默认道具。

例如:

shapes.js

export const CookiePreferenceButton = PropTypes.shape({
  ...
});

Foo.jsx

import { CookiePreferenceButton } from './shapes';

...

Foo.propTypes = {
  cookies: CookiePreferenceButton,
}

Bar.jsx

import { CookiePreferenceButton } from './shapes';

...

Bar.propTypes = {
  cookies: CookiePreferenceButton,
}