首页 > 解决方案 > 用建议反应搜索组件,如何选择建议

问题描述

我有一个带有建议的组件搜索组件。我通过 javascript 创建建议。我可以打印所有建议,但是如何选择要放入占位符的建议元素?感谢您的答复。

搜索组件

import React, { useEffect, useState } from "react";
import api from "../../api/index";
import "./index.css";

export default function Search(query) {
  const [searchSchool, setSearchShool] = useState("");
  const [showSuggestions, setShowSuggestions] = useState(false);
  const [allSchools, setAllSchools] = useState([]);
  const inputRef = React.useRef(null);

  useEffect(() => {
    (async () => {
      const data = await api.getSchools();
      setAllSchools(data);
    })();
  }, []);

  const resultsAllSchools = !searchSchool
    ? allSchools
    : allSchools.filter(school => school.toLowerCase().includes(searchSchool));

  const handleOnclick = e => {
    e.preventDefault();
    const lowerCase = e.target.value.toLowerCase();
    setSearchShool(lowerCase);
    setShowSuggestions(true);
    if (e.target.value === "" || null) {
      setShowSuggestions(false);
    }
  };

  return (
    <>
      <form>
        <input
          className="select"
          type="text"
          placeholder="Cerca el teu centre educatiu"
          value={searchSchool}
          ref={inputRef}
          onChange={handleOnclick}
        ></input>
        <button>
        </button>
        <ul>
          {showSuggestions &&
            resultsAllSchools.map((item, i) => <li key={i}>{item}</li>)}
        </ul>
      </form>
    </>
  );
}

标签: reactjsformsinput

解决方案


推荐阅读