Reactjs 和 Flexbox:在渲染函数中包装 div 使 flex 变得困难

IT技术 javascript reactjs flexbox
2021-05-10 21:48:36

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

根据我对 React 的理解,所有组件的 jsx 元素都应该包含在一个 div 中。例如这有效:

return (
    <div className="com-container">
       <div className="other-stuff">
       </div>
    </div>
)

而这不会:

return (
    <div className="com-container">
    </div>
    <div className="other-stuff">
    </div>
)

然而,这让 flexbox 的行和列变得困难。例如说我们有这个 flex 关系。

<Parent Column Component /> //vertical flex
  <ChildRowComponent1 />    //horizontal flex
  <ChildRowComponent2 />    //horizontal flex
  <ChildRowComponent3 />    //horizontal flex

但是ChildRowComponent2&3可以动态换出 - 这导致我通过将ChildRowComponent2&3放入它们自己的组件中进行重构,但是由于所有渲染必须包含在单个 div 中,我得到了这个额外的 div,它会混淆 flex 方向。

<Parent Column Component />  //vertical flex
  <ChildRowComponent1 />     //horizontal flex
  <div>                      
    <ChildRowComponent2 />   //horizontal flex now broken
    <ChildRowComponent3 />   //horizontal flex now broken
  </div>

问题:

是否有 flexbox 技巧来处理这些情况,或者我只是在构建组件的方式上做错了什么?

2个回答

片段解决了这个问题。<div>包装子元素时不需要任何额外的元素。这不会向 DOM 添加额外的节点。

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

react片段文档

您可以将其设置为一个返回列表的函数,而不是创建一个将ChildRowComponent2&分组的组件3然后你可以在你的Parent组件中做到这一点

  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;
  },

如果您想知道为什么需要keyprops,这里有一个解释