如何在自动完成中突出显示搜索文本?

时间:2020-07-08 00:48:25

标签: javascript reactjs

我正在尝试使一个自定义自动完成功能能够实现,但是我无法突出显示匹配的文本

这是我的代码 https://codesandbox.io/s/affectionate-colden-7embr?file=/src/index.js

查看我何时键入<Input type="text" name="hora_leitura" placeholder="2020-06-12T09:00:00.000" onChange={this.onChange} // this is what was missing required /> john以蓝色突出显示 enter image description here

john

matchItems = (items, regexp) => { let match = false; items.forEach(item => { if (item.search(regexp) > -1) { match = true; } }); return match; }; filterUsers = (users, regexp) => { const filteredUsers = users.filter( user => user.name.search(regexp) > -1 || user.id.search(regexp) > -1 || this.matchItems(user.items, regexp) || user.address.search(regexp) > -1 || user.pincode.search(regexp) > -1 ); return filteredUsers; }; filterByKeyword = e => { const keyword = e.target.value; this.setState({ currentInput: keyword }); if (keyword) { const regexp = new RegExp(`${keyword}`, 'i'); this.setState({ users: this.filterUsers(users, regexp) }); } else { this.setState({ users }); } };

所以我当前的代码是这样的,没有突出显示 enter image description here

2 个答案:

答案 0 :(得分:1)

您应将import SwiftUI struct ContentView: View { var body: some View { Rectangle() .fill(Color.red) .frame(width: 200, height: 200) } } 传递给currentInput作为填充匹配单词的道具。试试这个:

Name.js

Edit Select with checkboxes and sub headers

答案 1 :(得分:0)

我做到了,而且可行:

const User = React.forwardRef((props, ref) => {
  const { id, name, items, address, pincode } = props.data;
  const { input } = props;

  const formatLabel = label => {
    if (!input) {
      return label;
    }
    return (
      <span>
        {label.split(input).reduce((prev, current, i) => {
          if (!i) {
            return [current];
          }
          return prev.concat(<b key={input + current}>{input}</b>, current);
        }, [])}
      </span>
    );
  };

  let classes = "user";
  if (props.focused) {
    classes += " focused";
  }
  const handleMouseEvent = () => {
    props.handleMouseEvent(props.divId);
  };
  return (
    <div
      tabIndex="0"
      id={props.divId}
      ref={ref}
      className={classes}
      onKeyDown={props.handleKeyPress}
      onMouseMove={handleMouseEvent}
    >
      <Id id={formatLabel(id)} />
      <Name name={formatLabel(name)} />
      <Items items={items.map(item => formatLabel(item))} />
      <Address address={formatLabel(address)} pincode={formatLabel(pincode)} />
    </div>
  );
});

您需要向下传递currenInput值,直到用户组件为止。

此解决方案中的问题是它区分大小写:(

您可以尝试使用其他类似方法:

const { input } = props;
  const regexp = new RegExp(`${input}`, 'i');
  
  const formatLabel = label => {
    const formatedLabel = label.replace(regexp, '<b>$&</b>');
    return `<p>${formatedLabel}</p>`
  };

在ID组件(和其他组件)内部使用此渲染方法:

const Id = props => {
  return <div dangerouslySetInnerHTML={{__html: props.id}} />;
};