// utility hook
function useMouseOver() {
const [mouseOver, setMouseOver] = useState(false);
return {
mouseOver,
triggers: {
onMouseEnter: () => setMouseOver(true),
onMouseLeave: () => setMouseOver(false),
},
};
}
// mark component
function CommentHighlight({ attributes, children, ...props }) {
const { mouseOver, triggers } = useMouseOver();
return (
<span
{...attributes}
{...triggers}
style={{
background: mouseOver ? yellow[600] : yellow[200],
cursor: 'pointer',
}}
>
{children}
</span>
);
}
想象2个重叠的注释,它们具有不同的标记,但使用相同的CommentHighlight
分量呈现:
-----
---------
aaaccbbbbbbb
a
-具有注释1的标记b
-具有注释2的标记c
-注释1和2带有标记aaa
上时,我也需要cc
来更改颜色。但是如何?我唯一的猜测是跟踪redux(或类似)中的突出显示状态,并在状态更改时更新每个注释组件。但是,这看起来有些矫kill过正。
答案 0 :(得分:0)
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
const [back, setback] = React.useState(false);
const changeback = value => {
setback(value);
};
return (
<React.Fragment>
<CommentHighlight change={back} changeit={e => changeback(e)}>
aaa
</CommentHighlight>
<CommentHighlight change={back} changeit={e => changeback(e)}>
aaa
</CommentHighlight>
</React.Fragment>
);
}
function useMouseOver(changeit) {
const [mouseOver, setMouseOver] = React.useState(false);
return {
mouseOver,
triggers: {
onMouseEnter: () => {
setMouseOver(true);
changeit(true);
},
onMouseLeave: () => {
setMouseOver(false);
changeit(false);
}
}
};
}
// mark component
function CommentHighlight({ attributes, children, ...props }) {
const { mouseOver, triggers } = useMouseOver(props.changeit);
return (
<span
{...attributes}
{...triggers}
style={{
background: props.change ? "yellow" : "blue",
cursor: "pointer"
}}
>
{children}
</span>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
我不知道这是否是您正在寻找的方法,但是当您将鼠标悬停在第一个CommentHighlight上时,第二个颜色将变为,反之亦然