首页 > 解决方案 > 如何在 ag-grid react 中设置自定义过滤器对话框的焦点?

问题描述

我们正在开发一个将与屏幕阅读器一起使用的网格。到目前为止,ag-grid 很容易访问,但一个问题是在打开自定义过滤器时将焦点设置在它上面。(请注意,内置过滤器确实可以正确设置焦点。)

以前版本的网格有一个函数“afterGuiAttached()”,可用于在渲染后设置焦点。但是我们正在使用 ag-grid-community 25.1.0 和 ag-grid-react 25.1.0 并且该功能不再存在。

这是一个 plunker 示例,我在下面粘贴了一个示例自定义过滤器。 Plunker 示例

import React, {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useState,
  useRef,
} from 'react';

export default forwardRef((props, ref) => {
  const [filterText, setFilterText] = useState(null);

  // expose AG Grid Filter Lifecycle callbacks
  useImperativeHandle(ref, () => {
    return {
      doesFilterPass(params) {
        // make sure each word passes separately, ie search for firstname, lastname
        let passed = true;
        filterText
          .toLowerCase()
          .split(' ')
          .forEach((filterWord) => {
            const value = props.valueGetter(params);

            if (value.toString().toLowerCase().indexOf(filterWord) < 0) {
              passed = false;
            }
          });

        return passed;
      },

      isFilterActive() {
        return filterText != null && filterText !== '';
      },

      getModel() {
        return { value: filterText };
      },

      setModel(model) {
        setFilterText(model.value);
      },
    };
  });

  const onChange = (event) => {
    setFilterText(event.target.value);
  };

  useEffect(() => {
    props.filterChangedCallback();
  }, [filterText]);

  return (
    <div style={{ padding: 4, width: 200 }}>
      <div style={{ fontWeight: 'bold' }}>Custom Athlete Filter</div>
      <div>
        <input
          style={{ margin: '4 0 4 0' }}
          type="text"
          value={filterText}
          onChange={onChange}
          placeholder="Full name search..."
        />
      </div>
      <div style={{ marginTop: 20 }}>
        This filter does partial word search on multiple words, eg "mich phel"
        still brings back Michael Phelps.
      </div>
      <div style={{ marginTop: 20 }}>
        Just to emphasise that anything can go in here, here is an image!!
      </div>
      <div>
        <img
          src="https://www.ag-grid.com/images/ag-Grid2-200.png"
          style={{
            width: 150,
            textAlign: 'center',
            padding: 10,
            margin: 10,
            border: '1px solid lightgrey',
          }}
        />
      </div>
    </div>
  );
});

标签: reactjsaccessibilityag-grid

解决方案


我想我迟到了这个问题,但我遇到了同样的问题,我找到了解决方法。我正在使用 ag-grid community v26.2.0。我解决它的方法如下。

基本上,你给你的输入一个 ID,然后在onFilterOpened事件上,你直接关注 DOM 元素本身。当然,setTimeout()如果您在弹出窗口进入 DOM 时设置了一些动画,则可以添加一个小的延迟。

<AgGridReact
   {...otherGridOptions}
   onFilterOpened={() => document.querySelector("#idOfYourInput")?.focus()}>
   //columns or other children
</AgGridReact>

推荐阅读