跨共享组件的 React js 和 PropTypes 重复

React js and PropTypes repetition across shared components

我创建了一些 React 组件,因此 parent... 获得了一些道具...

每个后续 child 然后使用这些道具中的大部分,然后 children of children.

**--> Parent**
(required props)
**-------> child**
(required props)
**-------> child**
(required props)
**------------> sub child**
(required props)
**------------> sub child**

那些 "required props" 对于所有这些组件都是相同的。似乎过分了,每当我更新 Parent 中的道具时,我就必须进入所有这些 children 并更新到(如果需要的话)。当然,它们是必需的和需要的,但很好奇是否有一个 shortcut/or 实现不需要这种重复。有什么想法吗?

谢谢

您可以将道具类型存储在一个对象中,然后合并到每个组件的 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))
};

spread operator 可能会派上用场:

import OtherComponent from './OtherComponent';

const MyComponent = ({ foo }) => (<OtherComponent {...foo} />);

MyComponent.propTypes = {
    foo: PropTypes.shape({ ...OtherComponent.propTypes }),
};

export default MyComponent;