文档
组件
筛选方面
添加自定义筛选

示例:添加自定义过滤器输入搜索框

search_settings 添加一个新的过滤器属性。

当应用 writers 过滤器时,将向查询添加一个匹配过滤器子句。

{
  search_settings: {
    filter_attributes: [
      {
        attribute: 'writers',
        type: 'string',
        field: 'writers',
        filterQuery: (field, value) => {
          return {
            match: {
              [field]: value,
            },
          };
        },
      }
    ]
  }
}

使用 createConnector 添加一个新的自定义组件来处理 writers 过滤器的输入状态和筛选。

import React, { useState } from "react";
import { createConnector } from "react-instantsearch-dom";
 
const writersInputConnector = createConnector({
  displayName: "writers",
  getProvidedProps: (props, searchState) => {
    return {
      writers: searchState.writers || "",
    };
  },
  refine: (props, searchState, nextValue) => {
    return {
      ...searchState,
      writers: nextValue,
    };
  },
  getSearchParameters(searchParameters, props, searchState) {
    const { writers = "" } = searchState;
 
    if (!writers) return searchParameters;
 
    return searchParameters
      .addFacet("writers")
      .addFacetRefinement("writers", writers);
  },
});
 
const WritersSearchInput = writersInputConnector(({ refine }) => {
  const [query, setQuery] = useState("");
  return (
    <form onSubmit={(e) => {
      e.preventDefault(); refine(query)
    }}>
      <input
        type="text"
        className="ais-SearchBox-input"
        placeholder="search writers"
        value={query}
        onChange={(e) => {
          setQuery(e.target.value);
        }}
      />
    </form>
  );
});
 

Apache 2.0 2024 © Joseph McElroy。
需要帮助?加入 Discord