如何创建用于搜索多个对象键值的 React 搜索过滤器

IT技术 javascript reactjs loops
2021-05-17 09:38:33

我想为我的数据数组创建一个搜索过滤器。它有多个像这样的对象和键,

[
    {
        "fname": "Jayne",
        "lname": "Washington",
        "email": "jaynewashington@exposa.com",
        "gender": "female"
    },
    {
        "fname": "Peterson",
        "lname": "Dalton",
        "email": "petersondalton@exposa.com",
        "gender": "male"
    },
    {
        "fname": "Velazquez",
        "lname": "Calderon",
        "email": "velazquezcalderon@exposa.com",
        "gender": "male"
    },
    {
        "fname": "Norman",
        "lname": "Reed",
        "email": "normanreed@exposa.com",
        "gender": "male"
    }
]

我想搜索过滤器搜索这个数组上的任何地方。例如:当我输入输入框时,我想搜索对象内的任何地方。像 fname,lname,email,gender

我该怎么做?请帮我

如果我想限制只搜索名字和姓氏怎么办?

3个回答

您可以filter在组件状态中保留一个值,并使用它来查看它是否作为子字符串包含在任何数组元素属性中。

例子

class App extends React.Component {
  state = {
    filter: "",
    data: [
      {
        fname: "Jayne",
        lname: "Washington",
        email: "jaynewashington@exposa.com",
        gender: "female"
      },
      {
        fname: "Peterson",
        lname: "Dalton",
        email: "petersondalton@exposa.com",
        gender: "male"
      },
      {
        fname: "Velazquez",
        lname: "Calderon",
        email: "velazquezcalderon@exposa.com",
        gender: "male"
      },
      {
        fname: "Norman",
        lname: "Reed",
        email: "normanreed@exposa.com",
        gender: "male"
      }
    ]
  };

  handleChange = event => {
    this.setState({ filter: event.target.value });
  };

  render() {
    const { filter, data } = this.state;
    const lowercasedFilter = filter.toLowerCase();
    const filteredData = data.filter(item => {
      return Object.keys(item).some(key =>
        item[key].toLowerCase().includes(lowercasedFilter)
      );
    });

    return (
      <div>
        <input value={filter} onChange={this.handleChange} />
        {filteredData.map(item => (
          <div key={item.email}>
            <div>
              {item.fname} {item.lname} - {item.gender} - {item.email}
            </div>
          </div>
        ))}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>

多个对象键值的搜索过滤器并突出显示搜索词

实现了两个功能 -highlighterfilterHandler.

filterHandler 函数根据给定的输入过滤数据,然后将过滤后的数据发送到荧光笔函数进行高亮显示。

highlighter 函数接受两个参数 obj 和 input 并以字符串形式返回可突出显示的 HTML 代码。

class App extends React.Component {
  state = {
    input: "",
    fData: [{
        fname: "Jayne",
        lname: "Washington",
        email: "jaynewashington@exposa.com",
        gender: "female"
      },
      {
        fname: "Peterson",
        lname: "Dalton",
        email: "petersondalton@exposa.com",
        gender: "male"
      },
      {
        fname: "Velazquez",
        lname: "Calderon",
        email: "velazquezcalderon@exposa.com",
        gender: "male"
      },
      {
        fname: "Norman",
        lname: "Reed",
        email: "normanreed@exposa.com",
        gender: "male"
      }
    ],
    data: [{
        fname: "Jayne",
        lname: "Washington",
        email: "jaynewashington@exposa.com",
        gender: "female"
      },
      {
        fname: "Peterson",
        lname: "Dalton",
        email: "petersondalton@exposa.com",
        gender: "male"
      },
      {
        fname: "Velazquez",
        lname: "Calderon",
        email: "velazquezcalderon@exposa.com",
        gender: "male"
      },
      {
        fname: "Norman",
        lname: "Reed",
        email: "normanreed@exposa.com",
        gender: "male"
      }
    ]
  };


  handleChange = event => {
    this.setState({
      input: event.target.value
    }, this.filterHandler);
  };

  highlighter = (obj, lowercasedInput) => {
    let rawObj = obj.replace(`<span class='highlight'>`, '').replace(`</span>`, '');

    if (rawObj.indexOf(lowercasedInput) != -1) {
      const startIndex = rawObj.indexOf(lowercasedInput);
      const endIndex = startIndex - 1 + lowercasedInput.length;

      if (startIndex != 0) {
        return rawObj.slice(0, startIndex) + `<span class='highlight'>${lowercasedInput}</span>` + rawObj.slice(endIndex + 1, rawObj.length);
      } else {
        return rawObj.slice(0, startIndex) + `<span class='highlight'>${lowercasedInput}</span>` + rawObj.slice(endIndex + 1, rawObj.length);
      }
    } else {
      return rawObj
    }
  }


  filterHandler = () => {
    const {
      input,
      data
    } = this.state;
    const lowercasedInput = input.toLowerCase();

    const filteredData = data.filter(item => {
      return Object.keys(item).some(key =>
        item[key].toLowerCase().includes(lowercasedInput)
      );
    });

    let highlightFD = [];
    filteredData.map((values, index) => {
      highlightFD.push({ ...values
      });
    })


    if (lowercasedInput.trim().length > 0) {
      highlightFD.map((val, index) => {
        for (let key in val) {
          highlightFD[index][key] = this.highlighter(val[key].toLowerCase(), lowercasedInput);
        }
      });
    }

    this.setState({
      fData: highlightFD
    });

  }

  render() {
    const {
      input,
      fData
    } = this.state;



    return ( <
        div >
        <
        input value = {
          input
        }
        onChange = {
          this.handleChange
        }
        /> {
        fData.map(item => ( <div key ={item.email} className = "results" >
         <div dangerouslySetInnerHTML = {{__html: item.fname}}/>&nbsp;|&nbsp; 
         <div dangerouslySetInnerHTML = {{__html: item.lname}}/>&nbsp;|&nbsp; 
         <div dangerouslySetInnerHTML = {{__html: item.gender}}/>&nbsp;|&nbsp; 
          <div dangerouslySetInnerHTML = {{__html: item.email}}/>  
        </div >
        ))
      } </div>
  );
}
}

ReactDOM.render( < App / > , document.getElementById("root"));
.results {
  display: flex
}

span {
  background-color:black;
  color:white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>

注意: risklySetInnerHTML 是 React 在浏览器 DOM 中使用 innerHTML 的替代品。一般来说,从代码中设置 HTML 是有风险的,因为很容易在不经意间将用户暴露给跨站点脚本 (XSS) 攻击。

阅读更多:https : //reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml

使用正则表达式:

class App extends React.Component {
  state = {
    input: "",
    fData: [{
        fname: "Jayne",
        lname: "Washington",
        email: "jaynewashington@exposa.com",
        gender: "female"
      },
      {
        fname: "Peterson",
        lname: "Dalton",
        email: "petersondalton@exposa.com",
        gender: "male"
      },
      {
        fname: "Velazquez",
        lname: "Calderon",
        email: "velazquezcalderon@exposa.com",
        gender: "male"
      },
      {
        fname: "Norman",
        lname: "Reed",
        email: "normanreed@exposa.com",
        gender: "male"
      }
    ],
    data: [{
        fname: "Jayne",
        lname: "Washington",
        email: "jaynewashington@exposa.com",
        gender: "female"
      },
      {
        fname: "Peterson",
        lname: "Dalton",
        email: "petersondalton@exposa.com",
        gender: "male"
      },
      {
        fname: "Velazquez",
        lname: "Calderon",
        email: "velazquezcalderon@exposa.com",
        gender: "male"
      },
      {
        fname: "Norman",
        lname: "Reed",
        email: "normanreed@exposa.com",
        gender: "male"
      }
    ]
  };


  handleChange = event => {
    this.setState({
      input: event.target.value
    }, this.filterHandler);
  };

  highlighter = (obj, lowercasedInput) => {
    let rawObj = obj.replace(`<span class='highlight'>`, '').replace(`</span>`, '');

    if (rawObj.indexOf(lowercasedInput) != -1) {
      const startIndex = rawObj.indexOf(lowercasedInput);
      const endIndex = startIndex - 1 + lowercasedInput.length;

      if (startIndex != 0) {
        return rawObj.slice(0, startIndex) + `<span class='highlight'>${lowercasedInput}</span>` + rawObj.slice(endIndex + 1, rawObj.length);
      } else {
        return rawObj.slice(0, startIndex) + `<span class='highlight'>${lowercasedInput}</span>` + rawObj.slice(endIndex + 1, rawObj.length);
      }
    } else {
      return rawObj
    }
  }


  filterHandler = () => {
    const {
      input,
      data
    } = this.state;
    const lowercasedInput = input.toLowerCase();

    const filteredData = data.filter(item => {
      return Object.keys(item).some(key =>{
         const regex= new RegExp(`^${lowercasedInput.trim()}`,'i');
            return regex.test(item[key].toLowerCase()) ;
         }
      );
    });

    let highlightFD = [];
    filteredData.map((values, index) => {
      highlightFD.push({ ...values
      });
    })


    if (lowercasedInput.trim().length > 0) {
      highlightFD.map((val, index) => {
        for (let key in val) {
          highlightFD[index][key] = this.highlighter(val[key].toLowerCase(), lowercasedInput);
        }
      });
    }

    this.setState({
      fData: highlightFD
    });

  }

  render() {
    const {
      input,
      fData
    } = this.state;



    return ( <
        div >
        <
        input value = {
          input
        }
        onChange = {
          this.handleChange
        }
        /> {
        fData.map(item => ( <div key ={item.email} className = "results" >
         <div dangerouslySetInnerHTML = {{__html: item.fname}}/>&nbsp;|&nbsp; 
         <div dangerouslySetInnerHTML = {{__html: item.lname}}/>&nbsp;|&nbsp; 
         <div dangerouslySetInnerHTML = {{__html: item.gender}}/>&nbsp;|&nbsp; 
          <div dangerouslySetInnerHTML = {{__html: item.email}}/>  
        </div >
        ))
      } </div>
  );
}
}

ReactDOM.render( < App / > , document.getElementById("root"));
.results {
  display: flex
}

span {
  background-color:black;
  color:white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>

fData.filter((person) => {
  return object
    .value(person)
    .join('')
    .toLowerCase()
    .include(searchinput.toLowerCase())
})

searchinput是您在输入中键入的由状态控制的值。