账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    如何优雅的调整 React 组件内的子组件位置?
    37
    0

    基於 react-semantic-ui ,我组合出了一个可以 搜寻和换页的的 Table 组件。
    叫做 <PaginatedTable />

    working example: https://codesandbox.io/s/23q6...

    使用方式如下

    <PaginationTable
        items={[
          {
            id: 1,
            name: "test-item-1 ???"
          },
          {
            id: 2,
            name: "test-item-2"
          },
          {
            id: 3,
            name: "test-item-3"
          }
        ]}
        columnOption={[
          {
            header: "idHeader",
            cellValue: "id",
            onItemClick: item => {
              alert(item.id);
            },
            sortingField: "id"
          },
          {
            header: "Name~",
            cellValue: item =>
              `*custom text cannot be searched* property can item.name => ${
                item.name
              } `,
            onItemClick: item => {
              alert(item.name);
            },
            sortingField: "name"
          }
        ]}
        initSortingField={"id"}
        initSortingOrderAsc={false}
        pagination
        itemsPerPage={2}
        searchKeyProperties={["id", "name"]}
      />

    但这组件目前只能有固定的顺序如下:

    <PaginationTable>
     <SearchBar />
     <Table />
     <PaginationBar />
    </PaginationTable>

    而我在组件内其实并没有拆分 SearchBar, Table, PaginationBar 这样三个子组件。
    所以我无法利用 render props 的技巧去调整子组件的位置。
    若修改成 render props 後,就可这样使用调整子组件的位置:

    <PaginationTable {...其他 props}>
    {({ SearchBar, Table, PaginationBar  })=>
    <div>
     <SearchBar />
     <Table />
     <SearchBar />
    </PaginationTable>
    </div>
    </PaginationTable>
    

    当我尝试去改成 render props ,遇到很多麻烦,因为当拆成三个子组件时,我必须把原本用到 <PaginationTable> 中 this 的相关变数 ( this.state, this.props, this.xxxFunction ) 都修改,例如原本
    在 <PaginationTable> 中 用到 this.setState({ searchBarText: e.target.value }) 就必须改成修改很多写法才能传递下去

    
    <SearchBar onTextChange={()=>{
    
        this.setState({
            searchBarText: e.target.value
        });
    }} />
    

    请问有什麽方式可以做到,优雅的调整子组件的顺序,又不用特别为这件事情改成 render Props 的写法呢?
    又或者要怎麽更优雅的改成 render props 呢?

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 耳下落腮红 普通会员 1楼

      在React中,组件的位置通常是由其在父组件的JSX中定义的顺序决定的。如果你想调整子组件的位置,只需在父组件的render方法中重新排列它们。

      例如,假设你有以下组件结构:

      ```jsx return (

      ); ```

      如果你想将ChildComponentB移动到ChildComponentA前面,你可以这样做:

      ```jsx return (

      ); ```

      如果你需要更动态的方式控制子组件的位置,可以考虑使用数组和map函数来渲染子组件,根据某种条件排序这个数组:

      ```jsx const children = [/ 子组件数据 /]; children.sort((a, b) => a.order - b.order); // 假设每个子组件都有一个order属性用于排序

      return (

      {children.map((child, index) => ( ))}

      ); ```

      此外,也可以利用CSS进行布局调整,但这并不会改变DOM元素的实际顺序,仅仅是视觉上的位置变化。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部