简体   繁体   English

有没有一种方法可以将子组件添加到称为功能的功能性无状态组件中?

[英]Is there a way to add children components to functional stateless components that are called as functions?

I have a functional stateless component like so: 我有一个像这样的功能性无状态组件:

const Map = (props) => {
    ...
}

And I want to call it as a function inside of a container 我想将其作为容器内部的函数调用

{Map()}

Normally I know I can include children 通常我知道我可以包括孩子

<Map>
    <ChildComponent />
</Map>

Is there a way do the same thing while calling the component as a function? 将组件作为函数调用时,有没有办法做同样的事情?

I want to call it as a function , yes you can. 我想将其称为函数 ,可以。 But then you will have to restructure your components and it will come at come cost. 但是,随后您将不得不重组组件,而这将付出一定的代价。 You cannot use them interchangeably without some compromises. 您不能在没有任何妥协的情况下互换使用它们。

Following is a sample: 以下是一个示例:

 const Parent = function(props){ return ( <div> <h3> This is Parent</h3> { Array.isArray(props.children) ? props.children.map(x => typeof(x) === 'function' ? x() : x) : null } </div> ) } const Child = function(props){ return ( <p>This is Child! My name is {props.name}</p> ) } let JSX = Parent({ children: [ Child.bind(null, {name: 'foo'}), Child.bind(null, {name: 'Bar'}) ] }); ReactDOM.render(JSX, document.getElementById('content')); let JSX2 = ( <Parent> <Child name='Jon'/> </Parent> ) ReactDOM.render(JSX2, document.getElementById('content2')); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id='content'></div> <hr/> <div id='content2'></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM