I have an that links to another stateless component. I have an onClick listener that calls a method that calls e.preventDefault(), but this just makes the not link to anywhere when clicked.
constructor(props, context) {
super(props, context);
this.preventRefresh = this.preventRefresh.bind(this);
}
<a href={/components/Button'} onClick={this.preventRefresh}>{n.componentName}</a>
preventRefresh(e) {
e.preventDefault();
}
So clicking on the does nothinh. How can I prevent the page from reloading?
答案 0 :(得分:1)
在React中,这不起作用:
<a href={/components/Button'} onClick={this.preventRefresh}>{n.componentName}</a>
您不能将href属性设置为组件(组件不是URL)
如果要建立导航链接,则应使用react-router-dom(如果正在使用浏览器):
拳头,您必须安装它:
npm install --save react-router-dom
然后您可以使用它,请查看官方示例:
import React from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
const BasicExample = () => (
<Router>
<div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/topics">Topics</Link>
</li>
</ul>
<hr />
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/topics" component={Topics} />
</div>
</Router>
);
const Home = () => (
<div>
<h2>Home</h2>
</div>
);
const About = () => (
<div>
<h2>About</h2>
</div>
);
const Topics = ({ match }) => (
<div>
<h2>Topics</h2>
<ul>
<li>
<Link to={`${match.url}/rendering`}>Rendering with React</Link>
</li>
<li>
<Link to={`${match.url}/components`}>Components</Link>
</li>
<li>
<Link to={`${match.url}/props-v-state`}>Props v. State</Link>
</li>
</ul>
<Route path={`${match.url}/:topicId`} component={Topic} />
<Route
exact
path={match.url}
render={() => <h3>Please select a topic.</h3>}
/>
</div>
);
const Topic = ({ match }) => (
<div>
<h3>{match.params.topicId}</h3>
</div>
);
export default BasicExample;
并检查文档here