使用 reactjs 创建链接的覆盖

Create an override of a link with reactjs

本文关键字:覆盖 链接 创建 reactjs 使用      更新时间:2023-09-26

我想在 react 中创建一个自定义类型的链接,我可以像标签一样使用它,但它会覆盖 onClick 以尝试使用单页应用程序路由器。它将链接作为道具,并返回相同的链接,并覆盖点击事件。

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 中,您可以使用 JSX 转换器的 harmony 标志启用的 spread 运算符将任何用户定义的onClick从其他 props 中分离出来,然后使用 JSX 扩散属性将其余部分传递给<a>

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实现其Link组件的render()的方式,浅拷贝props然后覆盖那些需要由组件配置/处理的props:

  render: function () {
    var props = assign({}, this.props, {
      href: this.getHref(),
      className: this.getClassName(),
      onClick: this.handleClick
    });
    return React.DOM.a(props, this.props.children);
  }