[英]How to apply css to parent element when child focused in Mui V5?
作為一個簡單的演示,我制作了這個代碼沙箱示例。 當文本字段被聚焦時,我想將一些 styles 應用於 Box 組件。 在我的用例中,我可以在父框的文本字段的 class 瞬間應用 styles 。 但我想知道父框如何知道孩子是否專注,然后相應地應用 css。
最簡單的做法是處理文本字段的onFocus
和onBlur
事件,然后在文本框獲得焦點時向父元素添加額外的道具。
export default function FullWidthTextField() {
const [textFieldFocused, setTextFieldFocused] = React.useState(false);
const extraProps = textFieldFocused
? { backgroundColor: "orange" }
: {};
const sx = {
// ... default styles for the box
...extraProps
};
return (
<Box sx={sx}>
<TextField
fullWidth
label="fullWidth"
id="fullWidth"
onFocus={() => setTextFieldFocused(true)}
onBlur={() => setTextFieldFocused(false)}
/>
</Box>
);
}
這是一個更新的演示,展示了這個解決方案的實際效果。
這是我對 onFocus 事件和 onBlur 事件的解決方案:
演示: https://codesandbox.io/s/can-parent-know-child-focuses-sofq-material-demo-forked-sbjvl?file=/demo.js
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.