我正在创建一个组件,需要接收两组子组件并放置在组件的两个不同部分。
let CreditCardForm = ({icons, fields}) => (
<div>
<div className='some'>
<div className='special'>
<div className='nesting'>
{icons}
</div>
</div>
</div>
{fields}
</div>
)
let CreditCardFormUsage = () => {
let icons = () => (
<Icons>
<IconBogus/>
<IconVisa/>
<IconPaypal/>
<IconMore/>
</Icons>
)
let fields = () => (
<CreditCardFields>
<FieldCardNumber/>
<FieldName/>
<FieldExpirey/>
<FieldCCV/>
</CreditCardFields>
)
return (
<CreditCardForm icons={icons} fields={fields}/>
)
}
上面的代码应该可行,我的问题是可以根据元素本身的子元素获取这些属性值,并且有更自然的东西吗?
<CreditCardForm>
<Icons>
<IconBogus/>
<IconVisa/>
<IconPaypal/>
<IconMore/>
</Icons>
<CreditCardFields>
<FieldCardNumber/>
<FieldName/>
<FieldExpirey/>
<FieldCCV/>
</CreditCardFields>
</CreditCardForm>
答案 0 :(得分:4)
是的,this.props.children
将返回一个数组,因此如果您总是想加载特定的子项,那么只需在包装器中按索引引用这些子项。然后,您可以将icons
和fields
转换为包装器组件。这是一个有效的jsfiddle。了解render
的{{1}}方法如何正是您想要的。
CreditCardForm渲染:
App
字段和图标呈现:
<div>
<div className='some'>
<div className='special'>
<div className='nesting'>
{this.props.children[0]}
</div>
</div>
</div>
{this.props.children[1]}
</div>
App render:
<div>{this.props.children}</div>
答案 1 :(得分:1)
https://facebook.github.io/react/tips/children-props-type.html
当然,请查看 React.Children
https://facebook.github.io/react/docs/top-level-api.html#react.children