[英]How to filter an array of strings with an input
嗨,我正在使用 react 並有一個字符串數組
const themes = [
'light',
'dark',
'cupcake',
'bumblebee',
'emerald',
'corporate',
'synthwave',
'retro',
'cyberpunk',
'valentine',
'halloween',
'garden',
'forest',
'aqua',
'lofi',
'pastel',
'fantasy',
'wireframe',
'black',
'luxury',
'dracula',
'cmyk',
'autumn',
'business',
'acid',
'lemonade',
'night',
'coffee',
'winter',
]
我正在做的是像這樣映射它們
{themes.map((Theme) => (
<li
className={`${theme === Theme && 'btn-primary'} ${
input.includes(Theme) && "btn-primary"
}`}
key={Theme}
onClick={() => setTheme(`${Theme}`)}
>
<label>{Theme}</label>
</li>
))}
我在頂部有一個輸入 state
const [input, setInput] = useState('')
<input
type="text"
placeholder="Type here"
className="w-full max-w-xs py-3 mb-3 input input-bordered"
value={input}
onChange={(e) => setInput(e.target.value)}
/>
我嘗試使用常規過濾器方法,但我找不到一種方法來簡單地過濾字符串數組,如果輸入匹配或包含單個主題的字母來顯示?
您需要filter
map
之前的項目。
{themes.filter(t => t.toLowerCase().includes(input.toLowerCase())).map((Theme) => (
<li
className={`${theme === Theme && 'btn-primary'} ${
input.includes(Theme) && "btn-primary"
}`}
key={Theme}
onClick={() => setTheme(`${Theme}`)}
>
<label>{Theme}</label>
</li>
))}
當您的輸入更改時,它將重新渲染組件。 發生這種情況時,您可以調用startsWith
過濾掉任何以(或includes
)該值開頭的主題。
const { useState } = React; function Example({ themeData }) { const [ themes, setThemes ] = useState(themeData); const [ input, setInput ] = useState(''); // Accept the input, and return a filtered array function filterThemes(input) { return themes.filter(theme => { return theme.startsWith(input); }); } // Set the input function handleInput(e) { setInput(e.target.value); } return ( <main> <label for="themeInput"> Filter themes: <input value={input} id="themeInput" onInput={handleInput} /> </label> <ul> {filterThemes(input).map(theme => { return <li>{theme}</li>; })} </ul> </main> ); } const themes=["light","dark","cupcake","bumblebee","emerald","corporate","synthwave","retro","cyberpunk","valentine","halloween","garden","forest","aqua","lofi","pastel","fantasy","wireframe","black","luxury","dracula","cmyk","autumn","business","acid","lemonade","night","coffee","winter"]; ReactDOM.render( <Example themeData={themes} />, document.getElementById('react') );
input { margin-left: 0.25em; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="react"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.