2015-05-15 35 views
7

我已经创造了一些反应的组分,因此,父...得到一些道具共享组件...阵营js和PropTypes重复整个

再以后的每一次孩子使用大多数道具,那么孩子孩子的。

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

这些“所需道具”对于所有这些部件是相同的。似乎过度,每当我更新父母的道具,我必须进入所有这些孩子,并更新(如果他们是必需的)。当然,它们是必需的和需要的,但是如果有一个快捷方式/或者实现这个重复是没有必要的,那么它们很好奇。有任何想法吗?

感谢

+0

我不明白的问题。你是什​​么意思更新财产?你的意思是改变属性名称?喜欢在JavaScript文件中更改名称? 如果你正在讨论从父母到孩子的道具价值更新,那么这就是国家的用途,它应该根据那个父母的状态值更新任何子道具。 – PythonIsGreat

+1

是{... this.props}你想要什么?将所有道具传递给下一个组件。 –

回答

7

你可以存储在一个对象的道具类型,你合并到每个组件的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值只是一个对象。你如何构建这个对象完全取决于你。

+0

hmm。这似乎是可行的。但我不想让这种价值成为全球性的......否则,我还能如何将它融入每个孩子?感谢您的回应,顺便说一句,欣赏它。 – user1492442

+0

你如何组织你的代码取决于你。不需要将共享类型设置为全局,只需要在需要的地方访问即可。如果您正在使用模块,请将共享的道具作为模块并在需要时将其导入。 –

1

这很简单。如果你的写作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)) 
}; 
0

spread operator可能会派上用场:

import OtherComponent from './OtherComponent'; 

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

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

export default MyComponent;