Javascript 通过react ref获取锚点组件,并更新它';s href字段

Javascript 通过react ref获取锚点组件,并更新它';s href字段,javascript,reactjs,react-ref,create-ref,Javascript,Reactjs,React Ref,Create Ref,我有一个react代码,其中有“”组件。当我点击“”时,我想更改它的href字段。为此,我使用“ref”来获取“onclick”方法中的组件,如下所示: class SomeComponent { public ref: React.RefObject<any>; constructor(props: any) { super(props); this.ref = React.createRef(); } rende

我有一个react代码,其中有“”组件。当我点击“”时,我想更改它的href字段。为此,我使用“ref”来获取“onclick”方法中的组件,如下所示:

class SomeComponent {
    public ref: React.RefObject<any>;

    constructor(props: any) {
        super(props);
        this.ref = React.createRef();
    }

    render() {
        <a
          href="#"
          ref={ this.ref }
          onClick={this.clicked()}
        />
    } 

    private clicked() {
        const link = this.ref.current;
        link.href = "some_link"; // This doesn't have any effect on the "a" element
    }
}
class组件{
公共参考:React.reobject;
构造器(道具:任何){
超级(道具);
this.ref=React.createRef();
}
render(){
} 
私人点击(){
const link=this.ref.current;
link.href=“some_link”;//这对“a”元素没有任何影响
}
}

但结果是“href”没有得到更新。单击后它也将保持为“#”。你知道我该怎么做吗?

你发布的代码中有很多拼写错误或bug:

  • 缺少
    extensed React.Component
  • render()
    中缺少
    return
  • 调用
    this.clicked()
    ,而不是将函数传递给
    onClick
  • 在分配给
    链接之前,不检查该链接是否为
    null
  • 不在click事件上调用
    e.preventDefault()
    ,以防止重新链接到“#”
您可以修复所有这些错误,而且大部分都可以工作,但是如果组件出于任何原因重新渲染,则
href
将返回到
“#”
,因为这是
渲染()中设置的


我认为您应该将
onClick={this.clicked()}
更改为
onClick={this.clicked}
。因为您正在调用click,而不是传递其引用。您是否也希望重定向到链接发布click?我只希望更新href。单击会被调用,链接也会被提取。但是href不会因此而更新。
class SomeComponent extends React.Component {
  public ref: React.RefObject<HTMLAnchorElement>;

  constructor(props: {}) {
    super(props);
    this.ref = React.createRef();
  }

  render() {
    return (
      <a href="#" ref={this.ref} onClick={this.clicked}>
        Anchor Text
      </a>
    );
  }

  private clicked = (e: React.MouseEvent) => {
    const link = this.ref.current;
    if (link && link.href === "#" ) {
      e.preventDefault();
      link.href = "some_link";
    }
  };
}
class SomeComponent extends React.Component<{}, { href: string }> {
  constructor(props: {}) {
    super(props);
    this.state = {
      href: "#"
    };
  }

  render() {
    return (
      <a href={this.state.href} onClick={this.clicked}>
        Anchor Text
      </a>
    );
  }

  private clicked = (e: React.MouseEvent) => {
    if ( this.state.href === "#" ) {
      e.preventDefault();
      this.setState({ href: "some_link" });
    }
  };
}