Javascript 使用 onClick 函数将样式“cursor:pointer”应用于所有 React 组件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34680463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Apply style "cursor: pointer" to all React components with onClick function
提问by chevin99
I would like to apply the style cursor:pointer
to all React elements that have an onClick function. I know I could do this to every element:
我想将该样式cursor:pointer
应用于所有具有 onClick 函数的 React 元素。我知道我可以对每个元素都这样做:
<a onClick={handleClick} style={{cursor:'pointer'}}>Click me</a>
or this:
或这个:
<a onClick={handleClick} className="someClassWithCursorPointer">Click me</a>
But I'd much rather be able to just do something like this to apply the style to all elements:
但我更愿意做这样的事情来将样式应用于所有元素:
<style>
[onclick] {
cursor: pointer;
}
</style>
But that won't work because there's no actual onclick
attribute in the rendered HTML of an element when using React's onClick
attribute.
但这行不通,因为onclick
在使用 React 的onClick
属性时,元素的渲染 HTML 中没有实际属性。
Fiddle: https://jsfiddle.net/roj4p1gt/
回答by Michelle Tilley
I am not certain there's a good way to do this automatically without using some sort of mechanism that intercepts the creation of React elements and modifies them (or perhaps source level transforms). For example, using Babel, you could use babel-plugin-react-transformand add a className
to all elements with an onClick
prop using something along these lines (warning: pseudocode):
我不确定是否有一种很好的方法可以在不使用某种机制来拦截 React 元素的创建并修改它们(或者可能是源级转换)的情况下自动执行此操作。例如,使用 Babel,您可以使用babel-plugin-react-transform并使用以下行(警告:伪代码)className
向所有带有onClick
道具的元素添加 a :
export default function addClassNamesToOnClickElements() {
return function wrap(ReactClass) {
const originalRender = ReactClass.prototype.render;
ReactClass.prototype.render = function render() {
var element = originalRender.apply(this, arguments);
return addClickClassNamesToApplicableElements(element);
}
return ReactClass;
}
}
function addClassNamesToApplicableElements(elem) {
if (!elem || typeof elem === "string") return elem;
const children = elem.children;
const modifiedChildren = elem.props.children.map(addClassNamesToApplicableElements);
if (elem.props.onClick) {
const className = elem.props.className || "";
return {
...elem,
props: {
...elem.props,
className: (className + " hasOnClick").trim(),
children: modifiedChildren
}
};
} else {
return {
...elem,
props: {
...elem.props,
children: modifiedChildren
}
}
};
}
Here's a quick exampleof the second part working: https://bit.ly/1kSFcsg
这是第二部分工作的快速示例:https: //bit.ly/1kSFcsg
回答by Andrzej Trzaska
You can do that easily with css:
您可以使用 css 轻松做到这一点:
a:hover {
cursor:pointer;
}