我有两个组件,两个组件共享相同的道具。
我可以通过直接将它们设置为其他组件默认道具来分配默认道具和propTypes
EG
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;
是的,您可以在组件之间共享默认道具。
例如:
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,
}
而不是使用来自其他组件的prop类型在单独的文件中定义prop类型,并在两个组件中使用它们:
export const CookieButton = {
// ... your prop types
}
// import CookieButton and use it
static defaultProps = CookieButton
// another component
static propTypes = CookieButton;