我正在使用React和Javascript,我不确定该在哪里添加函数.我的输入工作得很好——但我意识到我需要添加一个函数,或者能够接受用户输入的任何内容,并将字符串转换为小写格式.我试着把它放在输入字段中,但这只会迫使用户输入的内容以小写形式输入,所以它在那里不起作用.

const {useState} = React;

const SearchBar = (props) => {
  const [songSearch, setSongSearch, ] = useState("");

  function searchResults(event) {
    event.preventDefault();
    let response = props.songs.filter((song) => {
      if (song.album.includes(songSearch) || song.artist.includes(songSearch) || song.title.includes(songSearch) 
      || song.genre.includes(songSearch) || song.release_date.includes(songSearch)){ 
        return true;
      }
  });
    console.log(response)
    props.setSongs(response);
  }

  return (
    <div >
      <form onSubmit={searchResults}>
        <div>
          <input className="search-bar-input"
            type="text"
            value={songSearch}
            onChange={(e) => setSongSearch(e.target.value)}
            placeholder="Search by: Title, Artist, Album, Release Date and Genre"
          />{" "}
          <button className="submit-button" type="submit">Search</button>
        </div>  
      </form>
    </div>
  );
};

const fixedSongs = [...Array(10).keys()]
  .map(x => x+1)
  .map(id => ({
    album: `Album Num ${id}`,
    artist: `Artist Num ${id}`,
    title: `Title Num ${id}`,
    genre: `Genre Num ${id}`,
    release_date: `Release Date Num ${id}`
  }));

const Thingy = ({...props}) => {
  return (
    <div>
      <SearchBar songs={fixedSongs} setSongs={() => {}}/>
    </div>
  );
};

ReactDOM.render(
  <div>
    DEMO
    <Thingy />
  </div>,
  document.getElementById("rd")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="rd" />

推荐答案

const {useState} = React;

const SearchBar = (props) => {
  const [songSearch, setSongSearch] = useState("");

  function searchResults(event) {
    event.preventDefault();
    // obtain "lower-case" version of the user-input (songSearch)
    const lowerCaseSongSearch = songSearch.toLowerCase();
    // avoid listing every column to search by using below array
    const searchCols = ['album', 'artist', 'title', 'genre', 'release_date'];
    let response = props.songs.filter((song) => {
      // find if "songSearch"'s lower-case version exists in any 
      // of the 5 search-columns (ie, album, artist, etc)
      if (
        searchCols.some(          // if "some" element (album, artist, etc)
          k => song[k]            // has the lower-case version of "songSearch"
          .toLowerCase()          // matching the lower-case version of album, artist, etc
          .includes(lowerCaseSongSearch)
        )
      ) {                       // if lower-case matched, return "true"
        return true;
      }
  });
    console.log(response)
    props.setSongs(response);
  }

  return (
    <div >
      <form onSubmit={searchResults}>
        <div>
          <input className="search-bar-input"
            type="text"
            value={songSearch}
            onChange={(e) => setSongSearch(e.target.value)}
            placeholder="Search by: Title, Artist, Album, Release Date and Genre"
          />{" "}
          <button className="submit-button" type="submit">Search</button>
        </div>  
      </form>
    </div>
  );
};

const fixedSongs = [...Array(10).keys()]
  .map(x => x+1)
  .map(id => ({
    album: `Album Num ${id}`,
    artist: `Artist Num ${id}`,
    title: `Title Num ${id}`,
    genre: `Genre Num ${id}`,
    release_date: `Release Date Num ${id}`
  }));

const Thingy = ({...props}) => {
  return (
    <div>
      <SearchBar songs={fixedSongs} setSongs={() => {}}/>
    </div>
  );
};

ReactDOM.render(
  <div>
    DEMO
    <Thingy />
  </div>,
  document.getElementById("rd")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="rd" />

Javascript相关问答推荐

如何使用侧边滚动按钮具体滚动每4个格?

类型脚本中只有字符串或数字键而不是符号键的对象

如何在不创建新键的情况下动态更改 map 中的项目?

如何使用JavaScript将文本插入空div

函数返回与输入对象具有相同键的对象

映射类型定义,其中值对应于键

如何在JAVASCRIPT中临时删除eventListener?

使用父标签中的Find函数查找元素

如何在和IF语句中使用||和&;&;?

在D3条形图中对具有相同X值的多条记录进行分组

如何使本地html页面在重新加载时保持当前可隐藏部分的打开状态?

如何组合Multer上传?

未捕获的不变违规:即使在使用DndProvider之后也应使用拖放上下文

在Puppeteer中使用promise进行日志(log)记录时出现TargetCloseError

有没有办法在R中创建一张具有多个色标的热图?

计算对象数组中属性的滚动增量

如何从Reaction-Redux中来自API调用的数据中筛选值

Select 所有输入.值

如何导入我在Web Worker创建的函数?

Oracle APEX-如何调用Java脚本函数