[英]React js and PropTypes repetition across shared components
我已经创建了一些反应组件,因此,父...获得了一些道具......
然后,每个后来的孩子都会使用这些道具中的大多数,然后是儿童
**--> Parent**
(required props)
**-------> child**
(required props)
**-------> child**
(required props)
**------------> sub child**
(required props)
**------------> sub child**
那些“必需的道具”对于所有这些组件都是相同的。 似乎过多,每当我在Parent中更新道具时,我必须进入所有这些孩子并更新到(如果他们是必需的)。 当然,它们是必需的和需要的,但是如果有一个快捷方式/实现,则不需要这种重复。 有任何想法吗?
谢谢
您可以将prop类型存储在合并到每个组件的propTypes
的propTypes
:
var requiredPropTypes = {
foo: ...,
bar: ...
};
var ComponentA = React.createClass({
propTypes: {
...requiredPropTypes,
// ComponentA's prop types follow
// ...
},
// ...
});
var ComponentB = React.createClass({
propTypes: {
...requiredPropTypes,
// ComponentB's prop types follow
// ...
},
// ...
});
propTypes
的值只是一个对象。 如何构建该对象完全取决于您。
这很简单。 如果您编写es6代码,则可以使用导入的组件的形状
import React, { PropTypes } from 'react';
import { Button } from 'components';
const NewComponent = (props) => {
return (
{props.buttons.map((button) =>
<div>
<Button {...props} />
</div>
)}
);
}
NewComponent.propTypes = {
buttons: PropTypes.arrayOf(PropTypes.shape({ Button }.propTypes))
};
传播运算符可能很方便:
import OtherComponent from './OtherComponent';
const MyComponent = ({ foo }) => (<OtherComponent {...foo} />);
MyComponent.propTypes = {
foo: PropTypes.shape({ ...OtherComponent.propTypes }),
};
export default MyComponent;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.