我最近做了这样的事情
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中有没有更惯用的方法呢?
答案 0 :(得分:1)
我认为您的解决方案很好,但是您也可以创建一个自定义组件,该组件将组件/元素类型作为prop,将onHit
函数作为prop并将其用作所有事件的事件处理程序,并且扩展其余的道具。
示例
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>