【问题标题】:Using ref to find a nested element使用 ref 查找嵌套元素
【发布时间】:2021-01-23 10:59:00
【问题描述】:

我正在使用gridjs-react 库来创建一个表,如下所示:

<Grid
  columns={['Name', 'Email']}
  data={[
    ['John', 'john@example.com'],
    ['Mike', 'mike@gmail.com']
  ]}
  ref={tableRef}
  search={true}
  pagination={{
    enabled: true,
    limit: 1,
  }}
/>

但是,我想最终向 dom 添加一个项目来获得这个:

我考虑过使用ref,但我无法访问以下 div,因为它仅在组件 Grid 安装后呈现:(据我所知)

【问题讨论】:

  • 该字段是您突出显示的Search 组件。您不应使用 Search 字段向数据添加新值

标签: reactjs gridjs


【解决方案1】:

您可以在 useEffect 块中的所有内容呈现后访问网格引用:

useEffect(()=> {
    const grid = ref.current.wrapper.current; //--> grid reference
    const header = grid.querySelector(".gridjs-head"); //--> grid header
    const itemContainer = document.createElement("div"); //--> new item container
    header.appendChild(itemContainer);
    ReactDOM.render(<Input />, itemContainer); //--> render new item inside header
  }, []);

您需要使用css 来获取元素内所需的位置。

工作示例:https://stackblitz.com/edit/react-r5gsvw

【讨论】:

    【解决方案2】:

    或者只是为您想要的组件使用 CSS 解决方案。

    例如

    <div style={{ position: 'relative'}}>
        <Grid 
        ....
        />
    
        <MySearchComponent style={{ position: 'absolute', top: 0, right: 0 }} />
    </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-13
      • 1970-01-01
      • 1970-01-01
      • 2019-06-04
      相关资源
      最近更新 更多