我最近做了这样的事
onHit(functionCall)
{
let attr = {};
attr["onKeyPress"] = functionCall;
attr["onClick"] = functionCall;
attr["onTouchEnd"] = functionCall;
return attr;
}
这样我就可以在我的JSX中做到这一点
<a {...this.onHit((e)=>this.doSomething())} title="This has no href" tabIndex="0">This has no href</a>
一切都如预期的那样工作,按键、单击和触地都会触发相同的事件。
我创建了这个onHit
函数,因为我正在构建一个web应用程序,其中所有的动作控件都需要通过键盘、鼠标和触摸屏进行访问。
在继续使用我的自定义onHit
函数之前,在ReactJS中是否有一种更惯用的方法来做到这一点?
发布于 2018-08-12 13:29:17
我认为您的解决方案很好,但您也可以创建一个自定义组件,它将组件/元素类型作为支柱,onHit
函数用作支柱,并将其用作所有事件的事件处理程序,并传播其余的支持。
示例
function MyComponent({ element: Element, onHit, ...rest }) {
return (
<Element onKeyPress={onHit} onClick={onHit} onTouchEnd={onHit} {...rest} />
);
}
class App extends React.Component {
render() {
return (
<MyComponent
element={"a"}
onHit={() => console.log("hit!")}
title="This has no href"
tabIndex="0"
>
This has no href
</MyComponent>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
https://stackoverflow.com/questions/51809116
复制相似问题