gpt4 book ai didi

reactjs - React onClick 不会阻止浏览器设置 anchor 标记

转载 作者:行者123 更新时间:2023-12-04 03:05:36 24 4
gpt4 key购买 nike

我是 React 新手,遇到了使用链接标签的分页控件的问题。我的基本分页控件呈现如下:

<a href="#page2">Next</a>

呈现它的 JSX 定义如下所示:

<a href={"#page"+(this.props.pageIndex+1)} onClick={this.handleClick}>
{this.props.name}
</a>

问题是,当您单击下一步链接转到第 2 页时,浏览器最终会在 URL 栏中显示#page3,即使代码正确呈现第 2 页。(代码不会修改 URL。)在调试器中跟踪 JavaScript,我看到 window.location.href 停留在 #page1,然后跳转到 #page3。

我相信正在发生的事情是 React 正在拦截点击事件,并正确地重新呈现页面,然后浏览器的默认链接处理在下一个链接更改为指向 #page3 之后 触发而不是#page2。

我的分析正确吗?如果是这样,使浏览器在 URL 栏中显示 #page2 的正确方法是什么?

编辑:这是上下文中的简化代码:

class RecordList extends React.Component {
changePage(pageIndex) {
console.log("change page selected: "+pageIndex);
this.props.changePage(pageIndex);
return false;
}

render() {
...
nextLink = (<PagingLink name=" Next> "pageIndex={this.props.pageIndex+1} handleClick={() =>
this.changePage(this.props.pageIndex+1)}/>)

return (
...
<div className="paging-control">
<span>Page {this.props.pageIndex+1}</span>
{nextLink}
</div>
);
}
}

class PagingLink extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.props.handleClick(this.props.pageIndex)
}
render() {
return (
<span className="pageLink">
<a href={"#page"+(this.props.pageIndex+1)} onClick={this.handleClick}>
{this.props.name}
</a>
</span>
);
}
}

class App extends Component {
constructor() {
super();
this.state = {
pageSize: 20,
pageIndex: 0,
...
};
}

componentDidMount() {
var pageIndex = this.state.pageIndex;
if (window.location.hash.indexOf("#page") === 0) {
pageIndex = Number(window.location.hash.substring(5))-1;
this.setState((prevState) => {
return { pageIndex: pageIndex };
}, () => {
this.fetchRecords(pageIndex);
});
}
else {
this.fetchRecords(pageIndex);
}
}

fetchRecords(pageIndex) {
...
}

changePage(pageIndex) {
console.log("change page selected: "+pageIndex);
this.setState({pageIndex: pageIndex});
this.fetchRecords(pageIndex);
}

render() {
var content = (
<RecordList
records={this.state.records}
pageSize={this.state.pageSize}
pageIndex={this.state.pageIndex}
changePage={(pageIndex) => this.changePage(pageIndex)}
/>
)
return (
<div className="App">
...
{content}
</div>
);
}

最佳答案

阻止 anchor 上的默认事件:

handleClick(event) {
event.preventDefault()
this.props.handleClick(this.props.pageIndex)
}

关于reactjs - React onClick 不会阻止浏览器设置 anchor 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44833622/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com