React onClick 不会阻止浏览器设置锚标记

dav*_*ung 3 jsx reactjs

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

<a href="#page2">Next</a>
Run Code Online (Sandbox Code Playgroud)

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

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

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

我相信正在发生的事情是 React 正在拦截点击事件,并正确地重新呈现页面,然后浏览器的默认链接处理Next 链接更改为指向 #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>
  );
}
Run Code Online (Sandbox Code Playgroud)

Ji *_*aSH 5

防止锚点上的默认事件:

handleClick(event) {
    event.preventDefault()
    this.props.handleClick(this.props.pageIndex)
}
Run Code Online (Sandbox Code Playgroud)