自定义 react-gridjs 的表头

Customize tablehead of react-gridjs

不使用默认的搜索栏,我想按如下方式对其进行自定义:

  1. 在搜索栏前面添加一个按钮。
  2. 在搜索占位符中使用图标 (<i className="fa fa-search"/>)。

到目前为止,这是我的代码:

import { Grid, _ } from 'gridjs-react';

const tableColumns = [
  'Name',
  'Phone',
  {
    name: 'Custom component',
    formatter: (text) => _(<b>{text}</b>)
  }
]
const tableData = [
  ['John', 12345, 'myText1'],
  ['Mike', 67891, 'myText2'],
]

export default function myCustomGrid() {
  return (
    <Grid
      sort={true}
      search={true} // This adds the search inp
      columns={tableColumns}
      data={tableData}
      language={{
        search: {
          placeholder: ' Search...'
        }
      }}
      pagination={{
        enabled: true,
        limit: 2
      }}
    />
  );
}

这可能是 portal.

的一个很好的用例

这使我们能够更灵活地决定在何处呈现我们的按钮。使用门户网站,我们可以使按钮成为搜索输入的兄弟姐妹:

const gridjsHeadRoot = document.getElementsByClassName("gridjs-head");

class GridHeaderButton extends React.Component {
  constructor(props) {
    super(props);
    this.el = document.createElement("button");
    this.el.innerText = "Click";
    this.el.style.cssText = `
      background-color: #0069d9;
      color: #fff; 
      border-radius: .25rem;
      padding: .375rem .75rem;
      float: right
    `;
    this.el.onclick = function () {
      // Do something
    };
  }

  componentDidMount() {
    gridjsHeadRoot[0].appendChild(this.el);
  }

  componentWillUnmount() {
    gridjsHeadRoot[0].removeChild(this.el);
  }

  render() {
    return ReactDOM.createPortal(this.props.children, this.el);
  }
}

那么你可以这样使用它:

function MyCustomGrid() {
  return (
    <Grid
      sort={true}
      search={true} // This adds the search inp
      columns={tableColumns}
      data={tableData}
      language={{
        search: {
          placeholder: " Search...",
        },
      }}
      pagination={{
        enabled: true,
        limit: 2,
      }}
    />
  );
}

export default function App() {
  return (
    <div className="App">
      <MyCustomGrid />
      <GridHeaderButton />
    </div>
  );
}

放置 GridHeaderButton 的顺序在这里很重要。因为 GridHeaderButtonMyCustomGrid 内呈现的元素为目标,这意味着您应该将 GridHeaderButton 放在 CustomGrid 下方,否则它将不起作用。


Sandbox Example