使用 reactjs 创建 link 的覆盖
Create an override of a link with reactjs
我想在 React 中创建一个自定义类型 link,我可以像 a 标签一样使用它,但它会覆盖 onClick 以尝试使用单页应用程序路由器。它需要 link 作为道具,returns 同样的 link 返回并覆盖点击事件。
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;
}
});
这在功能上完全符合预期,但它非常粗糙并且依赖于使用对象的私有属性。 'right' 的方法是什么。
如 Transferring with ... in JSX, you can use the the spread operator enabled by the JSX Transformer's harmony
flag to split out any user-defined onClick
from the other props, then pass the rest to an <a>
using JSX Spread Attributes 中所述:
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>
}
})
或者,您可以手动配置 prop 覆盖,例如这就是 react-router implements its Link
component's render()
,浅拷贝 props 然后覆盖组件需要 configured/handled 的方式:
render: function () {
var props = assign({}, this.props, {
href: this.getHref(),
className: this.getClassName(),
onClick: this.handleClick
});
return React.DOM.a(props, this.props.children);
}
我想在 React 中创建一个自定义类型 link,我可以像 a 标签一样使用它,但它会覆盖 onClick 以尝试使用单页应用程序路由器。它需要 link 作为道具,returns 同样的 link 返回并覆盖点击事件。
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;
}
});
这在功能上完全符合预期,但它非常粗糙并且依赖于使用对象的私有属性。 'right' 的方法是什么。
如 Transferring with ... in JSX, you can use the the spread operator enabled by the JSX Transformer's harmony
flag to split out any user-defined onClick
from the other props, then pass the rest to an <a>
using JSX Spread Attributes 中所述:
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>
}
})
或者,您可以手动配置 prop 覆盖,例如这就是 react-router implements its Link
component's render()
,浅拷贝 props 然后覆盖组件需要 configured/handled 的方式:
render: function () {
var props = assign({}, this.props, {
href: this.getHref(),
className: this.getClassName(),
onClick: this.handleClick
});
return React.DOM.a(props, this.props.children);
}