Javascript 使用reactjs创建链接的覆盖
我想在react中创建一个自定义类型的链接,我可以像使用标记一样使用它,但它会覆盖onClick以尝试使用单页应用程序路由器。它将链接作为道具,并在覆盖click事件时返回相同的链接Javascript 使用reactjs创建链接的覆盖,javascript,reactjs,Javascript,Reactjs,我想在react中创建一个自定义类型的链接,我可以像使用标记一样使用它,但它会覆盖onClick以尝试使用单页应用程序路由器。它将链接作为道具,并在覆盖click事件时返回相同的链接 React.createClass({ render: function () { //super naughty but I cant think of a better way of overloading just this var oldOnClick = this.
React.createClass({
render: function () {
//super naughty but I cant think of a better way of overloading just this
var oldOnClick = this.props.a._store.props.onClick;
this.props.a._store.props.onClick = function () {
if (oldOnClick) {
oldOnClick();
}
router.navigate(this.props.a._store.props.href);
return false;//always false as were using a router
}.bind(this);
return this.props.a;
}
});
这在功能上与预期完全相同,但它的性能非常出色,并且依赖于使用对象的私有属性。“正确”的方法是什么。如中所述,您可以使用JSX Transformer的harmony
标志启用的扩展运算符从其他道具中拆分出任何用户定义的onClick
,然后将其余的传递给:
谢谢,这要整洁得多,它仍然有点不理想,因为我使用的是纯JS(不是jsx),这需要使用React.\u spread助手。我认为最好是将JSX中的代码单独编译到我的其他代码中,但我需要这样做,这有点遗憾。
var Link = React.createClass({
_onClick(e) {
if (this.props.onClick) {
this.props.onClick()
}
e.preventDefault()
router.navigate(this.props.href)
},
render() {
var {onClick, ...others} = this.props
return <a {...others} onClick={this._onClick}>{this.props.children}</a>
}
})
render: function () {
var props = assign({}, this.props, {
href: this.getHref(),
className: this.getClassName(),
onClick: this.handleClick
});
return React.DOM.a(props, this.props.children);
}