如何解决通过 react ref 获取锚组件,并更新它的 href 字段 只使用状态
我有一个反应代码,其中有“ ”组件。当我单击“”时,我想更改它的 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
}
}
但结果“href”没有得到更新。单击后它也保持为“#”。知道如何让它工作吗?
解决方法
您发布的代码中有很多错别字或错误:
- 缺少
extends React.Component
。 -
return
中缺少render()
。 - 调用
this.clicked()
而不是将函数传递给onClick
。 - 在分配之前不检查
link
不是null
。 - 不在点击事件上调用
e.preventDefault()
以防止重新呈现为“#”。
您可以修复所有这些错误,并且大部分会起作用,但是如果组件因任何原因重新渲染,则 href
将返回到 "#"
因为这是 render()
中设置的内容。
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";
}
};
}
只使用状态
当您是首先设置 href
的人时,通过 DOM 操作修改 href
没有任何意义。将 href
的当前值存储在 this.state
中并使用 href={this.state.href}
呈现您的链接。
我们仍然需要仅在 e.preventDefault()
为 href
时有条件地调用 "#"
所以这仍然是一个可以改进的奇怪设计。也许显示一个 div
直到它点击一个 a
之后?但根据您的要求,这将起作用:
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" });
}
};
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。