简体   繁体   English

使用Algolia InstantSearch.JS创建一个选择下拉列表

[英]Create a select dropdown with Algolia InstantSearch.JS

After a few days of creating an Algolia search form, now struggling with trying to create a simple select field with a list of colours. 在创建Algolia搜索表单几天后,现在正在努力创建一个带有颜色列表的简单选择字段。 The colour list itself is approx 50 colours long so typing this as options is not really an option, plus these change daily. 颜色列表本身大约有50种颜色,因此将其作为选项输入并不是一个真正的选项,而且每天都会更改。

I've managed to get a price range slider on there and pull through the options of the colour but I now need to loop through the colours and either return '...' and put within '' or create the select field itself. 我已经设法在那里得到一个价格范围滑块并拉出颜色的选项但我现在需要循环颜色并返回'...'并放入''或创建选择字段本身。

So far, I've got: 到目前为止,我有:

search.addWidget(
  instantsearch.widgets.menu({
    container: '#colour',
    attributeName: 'colour',
    limit: 10,
    indices: {
      header: 'Colour'
    }
  })
);

Is there anyway to reformat this into a select field? 无论如何都要将其重新格式化为选择字段? Also, the colour ranges still need to be selectable after one has already been selected so the end user can just change. 此外,在选择一个颜色范围后,仍需要选择颜色范围,以便最终用户可以进行更改。

Any guidance or help would be hugely appreciated. 任何指导或帮助将非常感激。

Thanks! 谢谢!

That's possible with InstantSearch.js' connectors. 这可以通过InstantSearch.js的连接器实现。 What you do is in the first render make a select, and on subsequent renders you change the value of the <option> s 你所做的是在第一个渲染中进行选择,然后在后续渲染中你改变<option>的值

import instantsearch from 'instantsearch.js';

function render(
  {items, refine, widgetParams: {containerNode, title}},
  isFirstRendering
) {
  let select;
  if (isFirstRendering) {
    const header = document.createElement('div');
    header.innerText = title;
    containerNode.appendChild(header);
    select = document.createElement('select');

    select.addEventListener('change', e => refine(e.target.value));

    containerNode.appendChild(select);
  } else {
    select = containerNode.querySelector('select');
  }

  const options = items.map(item => {
    const option = document.createElement('option');

    option.innerText = `${item.label} ${item.count}`;
    option.value = item.value;
    option.selected = item.isRefined;

    return option;
  });

  select.textContent = '';
  options.forEach(el => select.appendChild(el));
}

export default instantsearch.connectors.connectMenu(render);

You can then call this connected menu via the following way: 然后,您可以通过以下方式呼叫此连接菜单:

import selectMenu from './custom-widgets/selectMenu.js';

search.addWidget(selectMenu({
  containerNode: document.getElementById('#menu'),
  attributeName: 'brand',
  limit: 10,
  title: 'Brands',
}));

I know it's quite late, but let me know if this helps! 我知道现在已经很晚了,但请告诉我这是否有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM