Javascript Reactjs和Flexbox:在渲染函数中包装div使flex变硬

Javascript Reactjs和Flexbox:在渲染函数中包装div使flex变硬,javascript,reactjs,flexbox,Javascript,Reactjs,Flexbox,React让我在使用flexbox时遇到了麻烦,因为组件渲染函数中的包装div偏离了我的flex方向 <Parent Column Component /> //vertical flex <ChildRowComponent1 /> //horizontal flex <div> <ChildRowComponent2 /> //horizontal flex now br

React让我在使用flexbox时遇到了麻烦,因为组件渲染函数中的包装div偏离了我的flex方向

<Parent Column Component />  //vertical flex
  <ChildRowComponent1 />     //horizontal flex
  <div>                      
    <ChildRowComponent2 />   //horizontal flex now broken
    <ChildRowComponent3 />   //horizontal flex now broken
  </div>
根据我对React的理解,所有组件的jsx元素都应该封装在一个div中。例如:

return (
    <div className="com-container">
       <div className="other-stuff">
       </div>
    </div>
)
问题:
是否有flexbox技巧来处理这些情况,或者我只是在构建组件的方式上做错了什么?

您可以将它设置为一个返回列表的函数,而不是创建一个分组
ChildRowComponent2
&
3的组件。然后,您可以在
父组件中执行此操作:

  render: function() {
    return (
      <div className="main-container">
        <ChildRowComponent1 />
        { this.renderOtherChildren() }
      </div>
    )
  },
  renderOtherChildren: function () {
    var result = [];
    if (this.props.shouldHaveSecondChild) {
      result.push(<ChildRowComponent2 key={ 2 } />);
    }
    if (this.props.shouldHaveThirdChild) {
      result.push(<ChildRowComponent3 key={ 3 } />);
    }
    return result;
  },
render:function(){
返回(
{this.renderOtherChildren()}
)
},
renderOtherChildren:function(){
var结果=[];
如果(这个.道具.应该有第二个孩子){
结果:push();
}
如果(这个道具应该有第三个孩子){
结果:push();
}
返回结果;
},

如果您想知道为什么需要
道具,.

片段可以解决此问题。包装子元素时,不需要任何额外的
元素。这不会向DOM中添加额外的节点

return (
 <React.Fragment>
    <div className="com-container">
    </div>
    <div className="other-stuff">
    </div>
 <React.Fragment>
)
返回(
)

这是一个已知的问题,-遗憾的是还没有简单的解决方法。伟大的编辑@m01!很好地解决了这个问题!我会尝试一下,让你知道它是怎么回事。开放给其他人想出的解决方法。还有@m01,你能再详细说明一下你的答案吗?我从未见过另一个函数可能返回jsx或其他组件,因此查看其语法将非常有用。我将此添加到了答案中。我正在阅读您发布的链接。我会尝试一下,让每个人都知道结果是怎样的:)好吧,我认为你实际上可以重构你的路由器,这样它就可以返回关于哪些组件应该可见的信息,而不是呈现组件。然后您的
Parent
组件将在
props
中获取此信息并进行相应处理。(免责声明:我从未使用react路由器。)顺便说一句:
这个.props.children
是一个列表(例如,
[,]
),因此您可以像使用我的
renderherchildren
函数的输出一样使用它。
  render: function() {
    return (
      <div className="main-container">
        <ChildRowComponent1 />
        { this.renderOtherChildren() }
      </div>
    )
  },
  renderOtherChildren: function () {
    var result = [];
    if (this.props.shouldHaveSecondChild) {
      result.push(<ChildRowComponent2 key={ 2 } />);
    }
    if (this.props.shouldHaveThirdChild) {
      result.push(<ChildRowComponent3 key={ 3 } />);
    }
    return result;
  },
return (
 <React.Fragment>
    <div className="com-container">
    </div>
    <div className="other-stuff">
    </div>
 <React.Fragment>
)