我試圖制作一個帶有放大鏡圖示的搜索框,當輸入欄位聚焦時,該圖示變為藍色。
MagnifyingGlass 組件從其父元素繼承其顏色。
import styles from './Search.module.sass';
import { useState } from 'react';
import MagnifyingGlass from '../../icons/MagnifyingGlass';
const Search = () => {
const [inputValue, setInputValue] = useState('');
const handleChange = (e) => {
setInputValue(e.target.value);
};
return (
<div className={styles.searchWrapper}>
<input
value={inputValue}
onChange={handleChange}
className={styles.searchInput}
type='text'
placeholder='Waar bent u naar opzoek?'
/>
<span> // needs to contain a className that results in the color to change
<MagnifyingGlass size='small' /> // inherits color from parent
</span>
</div>
);
};
export default Search;
uj5u.com熱心網友回復:
您不需要更改父元素上的任何類,只需使用 css:focus-within偽選擇器即可。
根據 MDN,:focus-within CSS如果元素或其任何后代被聚焦,則偽類匹配元素。
這是一個例子:
.wrapper {
padding: 1rem;
width: fit-content;
border: 1px solid green;
}
.wrapper:focus-within {
border: 1px solid blue;
}
.wrapper p {
color: green;
}
.wrapper:focus-within p {
color: blue;
}
<div class="wrapper">
<p>this is a text</p>
<input type="text">
</div>
您可以在 MDN或CSS-Tricks上閱讀更多相關資訊
uj5u.com熱心網友回復:
使用 onFocus 和 onBlur 事件
const Search = () => {
const [inputValue, setInputValue] = useState('');
const [show, toggle] = useState(false);
const eventHandlers = useMemo(() => ({
onFocus: () => toggle(true),
onBlur: () => toggle(false),
}), []);
const handleChange = (e) => {
setInputValue(e.target.value);
};
return (
<div className={styles.searchWrapper}>
<input
value={inputValue}
onChange={handleChange}
className={styles.searchInput}
type='text'
placeholder='Waar bent u naar opzoek?'
{...eventHandlers}
/>
<span className={show ? 'your_class': ''}> // needs to contain a className that results in the color to change
<MagnifyingGlass size='small' /> // inherits color from parent
</span>
</div>
);
};
export default Search;
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/530756.html
