可搜索的输入在React.js中不起作用。

huangapple go评论61阅读模式
英文:

Searchable input is not working in React.js

问题

I want to create searchable input but something went wrong that's why this is not working. How can I fix it?

我的代码:

import React, { useState } from 'react';
import "./styles.css";

export default function App() {
  const country_list = [
    "Argentina",
    "Australia",
    "Belgium",
    "Belize",
    "China",
    "Iceland",
    "India",
    "Indonesia",
    "Iran",
    "Poland",
    "Portugal",
    "Romania",
    "Russia",
    "Saudi Arabia",
    "South Africa",
    "South Korea",
    "Swaziland",
    "Sweden",
    "Switzerland"
  ];

  const [inputVal, setInputVal] = useState();

  const filteredCountries = country_list.filter(country => {
    if (inputVal === '') {
      return true;
    } else if (country.toLowerCase().includes(inputVal.toLowerCase())) {
      return true;
    }
    return false;
  });

  return (
    <div className="App">
      <input type="text" onChange={event => setInputVal(event.target.value)} />
      {filteredCountries.map((val, index) => (
        <div key={index}>
          {val}
        </div>
      ))}
    </div>
  );
}

Please note that I've made some changes to your code to make the input filter the countries correctly. The filtered countries are stored in the filteredCountries array, and you should map over this array to display the filtered results.

英文:

I want to create searchable input but something went wrong that's why this is not working. How can I fix it?

My code:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

import React, {useState} from &#39;react&#39;;
import &quot;./styles.css&quot;;

export default function App() {
  const country_list = [
    &quot;Argentina&quot;,
    &quot;Australia&quot;,
    &quot;Belgium&quot;,
    &quot;Belize&quot;,
    &quot;China&quot;,
    &quot;Iceland&quot;,
    &quot;India&quot;,
    &quot;Indonesia&quot;,
    &quot;Iran&quot;,
    &quot;Poland&quot;,
    &quot;Portugal&quot;,
    &quot;Romania&quot;,
    &quot;Russia&quot;,
    &quot;Saudi Arabia&quot;,
    &quot;South Africa&quot;,
    &quot;South Korea&quot;,
    &quot;Swaziland&quot;,
    &quot;Sweden&quot;,
    &quot;Switzerland&quot;
  ];

  const [inputVal, setInputVal] = useState();

  country_list.filter(country =&gt; {
    if(inputVal === &#39;&#39;){
      return country;
    } else if (country.toLowerCase().includes(inputVal.toLowerCase())) {
      return country;
    }
  });

  return (
  &lt;div className=&quot;App&quot;&gt;
    &lt;input type=&quot;text&quot; onChange={event =&gt; setInputVal(event.target.value)} /&gt;
      {inputVal}
      {country_list.map((val, index)=&gt;(
        &lt;&gt;
        &lt;div key={index}&gt;
          {val}
        &lt;/div&gt;
        &lt;/&gt;
      ))}
  &lt;/div&gt;)
}

<!-- end snippet -->

答案1

得分: 1

I want to create searchable input but something went wrong thats why this is not working. How can i fix it?

Your code seems fine, just move it to the return block, before mapping:

{country_list.filter(country => {
  if(inputVal === ''){
    return country;
  } else if (country.toLowerCase().includes(inputVal.toLowerCase())) {
    return country;
  }
}).map((val, index) => ( ... )}
英文:

> I want to create searchable input but something went wrong thats why this is not working. How can i fix it?

Your code seems fine, just move it to the return block, before mapping:

  {country_list.filter(country =&gt; {
    if(inputVal === &#39;&#39;){
      return country;
    } else if (country.toLowerCase().includes(inputVal.toLowerCase())) {
      return country;
    }
  }).map((val, index)=&gt;( ... )}

答案2

得分: 1

为了使该代码工作,你应该修复一些字符串。我在下面发布了一些评论。此外,我建议将可更改的变量,如country_list,移动到useState中,因为应用的状态可能与视图不同步。

import React, { useState } from 'react';
import "./styles.css";

export default function App() {
  let country_list = [
    "Argentina",
    "Australia",
    "Belgium",
    "Belize",
    "China",
    "Iceland",
    "India",
    "Indonesia",
    "Iran",
    "Poland",
    "Portugal",
    "Romania",
    "Russia",
    "Saudi Arabia",
    "South Africa",
    "South Korea",
    "Swaziland",
    "Sweden",
    "Switzerland"
  ]; // 将country_list更改为let,以便我们可以重新分配它;

  const [inputVal, setInputVal] = useState(''); // 在useState中使用空字符串作为inputVal的初始状态

  country_list = country_list.filter(country => {
    if (inputVal === '') {
      return country;
    } else if (country.toLowerCase().includes(inputVal.toLowerCase())) {
      return country;
    }
  }); // JS中的filter函数每次都会创建一个新数组,而不是更改旧数组。你应该重新分配你的country_list变量

  return (
    <div className="App">
      <input type="text" onChange={event => setInputVal(event.target.value)} />
      {inputVal}
      {country_list.map((val, index) => (
        <>
          <div key={index}>
            {val}
          </div>
        </>
      ))}
    </div>)
}
英文:

To make that code work you should fix some strings. I posted comments bellow. Also I recommend move your changable variables like country_list to useState because the state of your app can get out of sync with the view.

import React, { useState } from &#39;react&#39;;
import &quot;./styles.css&quot;;

export default function App() {
  let country_list = [
    &quot;Argentina&quot;,
    &quot;Australia&quot;,
    &quot;Belgium&quot;,
    &quot;Belize&quot;,
    &quot;China&quot;,
    &quot;Iceland&quot;,
    &quot;India&quot;,
    &quot;Indonesia&quot;,
    &quot;Iran&quot;,
    &quot;Poland&quot;,
    &quot;Portugal&quot;,
    &quot;Romania&quot;,
    &quot;Russia&quot;,
    &quot;Saudi Arabia&quot;,
    &quot;South Africa&quot;,
    &quot;South Korea&quot;,
    &quot;Swaziland&quot;,
    &quot;Sweden&quot;,
    &quot;Switzerland&quot;
  ] // change country_list to let so we could reasssign it;

  const [inputVal, setInputVal] = useState(&#39;&#39;); // use empty string in useState as initial state for you inputVal 

  country_list = country_list.filter(country =&gt; {
    if (inputVal === &#39;&#39;) {
      return country;
    } else if (country.toLowerCase().includes(inputVal.toLowerCase())) {
      return country;
    }
  }); // function filter in JS create new array everytime instead of changing the old one. You should reassign your country_list variable

  return (
    &lt;div className=&quot;App&quot;&gt;
      &lt;input type=&quot;text&quot; onChange={event =&gt; setInputVal(event.target.value)} /&gt;
      {inputVal}
      {country_list.map((val, index) =&gt; (
        &lt;&gt;
          &lt;div key={index}&gt;
            {val}
          &lt;/div&gt;
        &lt;/&gt;
      ))}
    &lt;/div&gt;)
}

答案3

得分: 0

我相信使用这种方法会奏效,将你的代码移动到return()并将filter返回的值映射到下面的代码中,它就会起作用:

{countryList
  .filter((country) => {
    if (inputVal === "") {
      return country;
    } else if (country.toLowerCase().includes(inputVal.toLowerCase())) {
      return country;
    } 
  })
  .map((val, index) => {
    return (
      <div key={index}>
        {val}
      </div>
    );
  })}
英文:

I believe that using this going to work, move your code to the return () and map the returned value from the filter try this code below and its gonna work 可搜索的输入在React.js中不起作用。

{countryList
    .filter((country) =&gt; {
      if (inputVal == &quot;&quot;) {
        return country;
      } else if (country.toLowerCase().includes(inputVal.toLowerCase())) {
        return country;
      } 
    })
    .map((Val, index) =&gt; {
      return (
        &lt;div key={index}&gt;
          {val}
        &lt;/div&gt;
      );
    })}

答案4

得分: 0

你可以这样做,如果你想要数据:

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const country_list = [
    "Argentina",
    "Australia",
    "Belgium",
    "Belize",
    "China",
    "Iceland",
    "India",
    "Indonesia",
    "Iran",
    "Poland",
    "Portugal",
    "Romania",
    "Russia",
    "Saudi Arabia",
    "South Africa",
    "South Korea",
    "Swaziland",
    "Sweden",
    "Switzerland"
  ];

  const [inputVal, setInputVal] = useState(" ");

  const countryList = country_list.filter((country) => {
    if (inputVal === "") {
      return country;
    } else if (country.toLowerCase().includes(inputVal.toLowerCase())) {
      return country;
    }
    return country;
  });
  console.log(countryList);

  return (
    <div className="App">
      <input
        type="text"
        onChange={(event) => setInputVal(event.target.value)}
      />
      {inputVal}
      {countryList.map((val, index) => (
        <>
          <div key={index}>{val}</div>
        </>
      ))}
    </div>
  );
}
英文:

You can do like this if you want data

import React, { useState } from &quot;react&quot;;
import &quot;./styles.css&quot;;

export default function App() {
  const country_list = [
    &quot;Argentina&quot;,
    &quot;Australia&quot;,
    &quot;Belgium&quot;,
    &quot;Belize&quot;,
    &quot;China&quot;,
    &quot;Iceland&quot;,
    &quot;India&quot;,
    &quot;Indonesia&quot;,
    &quot;Iran&quot;,
    &quot;Poland&quot;,
    &quot;Portugal&quot;,
    &quot;Romania&quot;,
    &quot;Russia&quot;,
    &quot;Saudi Arabia&quot;,
    &quot;South Africa&quot;,
    &quot;South Korea&quot;,
    &quot;Swaziland&quot;,
    &quot;Sweden&quot;,
    &quot;Switzerland&quot;
  ];

  const [inputVal, setInputVal] = useState(&quot; &quot;);

  const countryList = country_list.filter((country) =&gt; {
    if (inputVal === &quot;&quot;) {
      return country;
    } else if (country.toLowerCase().includes(inputVal.toLowerCase())) {
      return country;
    }
    return country;
  });
  console.log(countryList);

  return (
    &lt;div className=&quot;App&quot;&gt;
      &lt;input
        type=&quot;text&quot;
        onChange={(event) =&gt; setInputVal(event.target.value)}
      /&gt;
      {inputVal}
      {countryList.map((val, index) =&gt; (
        &lt;&gt;
          &lt;div key={index}&gt;{val}&lt;/div&gt;
        &lt;/&gt;
      ))}
    &lt;/div&gt;
  );
}


huangapple
  • 本文由 发表于 2023年2月8日 17:16:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75383514.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定