如何创建\合并功能

时间:2019-07-15 15:24:50

标签: reactjs material-ui

我有重复的代码基本上控制了Raise背景。 我希望使用一个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 个答案:

答案 0 :(得分: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}>