开发者问题收集

如何创建\合并函数

2019-07-15
44

我有重复的代码,基本上控制凸起的背景。 我更喜欢一个 onMouseOver 和 OnMouseOut 函数,这样代码会更具可读性。

我认为这应该是一个自定义钩子,但不确定如何做到这一点。

谢谢

const [descRaised, setDescRaised] = useState(false);
const descOnMouseOver = () => { setDescRaised(true) }
const descOnMouseOut = () => { setDescRaised(false) }

const [inspRaised, setInspRaised] = useState(false);
const inspOnMouseOver = () => { setInspRaised(true) }
const inspOnMouseOut = () => { setInspRaised(false) }

<Grid item xs={6}>
                    <Card
                        id="descCard"
                        style={{ borderColor: green[500] }}
                        className={classes.card}
                        onMouseOver={descOnMouseOver}
                        onMouseOut={descOnMouseOut}
                        raised={descRaised}> .......


      <Card
                        style={{ borderColor: pink[500] }}
                        className={classes.card}
                        onMouseOver={inspOnMouseOver}
                        onMouseOut={inspOnMouseOut}
                        raised={inspRaised}>.........
1个回答

你可以使用单个 useState ,如下面的代码所示:

const [raised, setRaised] = useState({
   descCard: false,
   inspCard: false
});

const onMouseOver = (e) => { setRaised(prevState => ({ ...prevState, [e.target.id]: true }));}
const onMouseOut = (e) => { setRaised(prevState => ({ ...prevState, [e.target.id]: false})); }

<Grid item xs={6}>
                    <Card
                        id="descCard"
                        style={{ borderColor: green[500] }}
                        className={classes.card}
                        onMouseOver={onMouseOver}
                        onMouseOut={onMouseOut}
                        raised={descCard}> .......


      <Card id='inspCard'
                        style={{ borderColor: pink[500] }}
                        className={classes.card}
                        onMouseOver={onMouseOver}
                        onMouseOut={onMouseOut}
                        raised={inspCard}>
Monika Mangal
2019-07-15