[英]How to redirect to a gatsby-react page with an onclick event of a component?
I'm trying to redirect to a page using an onClick
event of a component.我正在尝试使用组件的
onClick
事件重定向到页面。 As I have react gatsby installation is it possible to use Link
from gatsby-link
to redirect.因为我有反应的盖茨比安装有可能使用
Link
从gatsby-link
重定向。
import React from 'react';
import { OverflowMenu, OverflowMenuItem } from '../Overflow';
import Link from 'gatsby-theme-carbon/src/components/Link';
class OverflowComponent extends React.Component {
editPage(index) {
console.log();
// window.location.href='/edit';
return(
<Link to="/edit"></Link> // I'm trying to redirect to Edit page
)
}
deletePage() {
console.log("Delete clicked");
}
render(){
return (
<div>
<OverflowMenu flipped={true}>
<OverflowMenuItem itemText="Edit" primaryFocus onClick={() => this.editPage()} />
<OverflowMenuItem itemText="Delete" onClick={() => this.deletePaget()} />
</OverflowMenu>
</div>
);
}
}
export default OverflowComponent;
from the above code the Overflow
component is a contributed component and it can have a onClick function.从上面的代码可以看出,
Overflow
组件是一个贡献组件,它可以有一个 onClick 函数。 And I'm trying to redirect using gatsby-link.我正在尝试使用 gatsby-link 进行重定向。
Instead of using Link or window.location as mentioned in the question we can use navigate
from gatsby
.我们可以使用从
gatsby
navigate
,而不是使用问题中提到的 Link 或 window.location 。 As shown below如下所示
import React from 'react';
import { OverflowMenu, OverflowMenuItem } from '../Overflow';
import {navigate} from 'gatsby'; //import navigate from gatsby
class OverflowComponent extends React.Component {
editPage(index) {
navigate('/edit'); //navigate to edit page
}
deletePage() {
console.log("Delete clicked");
}
render(){
return (
<div>
<OverflowMenu flipped={true}>
<OverflowMenuItem itemText="Edit" primaryFocus onClick={() => this.editPage()} />
<OverflowMenuItem itemText="Delete" onClick={() => this.deletePaget()} />
</OverflowMenu>
</div>
);
}
}
export default OverflowComponent;
<Link>
renders an anchor element ( <a href='...'>
). <Link>
呈现一个锚元素( <a href='...'>
)。 You would probably want to use navigate
here instead: https://www.gatsbyjs.org/docs/gatsby-link/#how-to-use-the-navigate-helper-function .您可能希望在此处使用
navigate
: https : //www.gatsbyjs.org/docs/gatsby-link/#how-to-use-the-navigate-helper-function 。
You might also need to use the onClick prop on the <OverflowMenuItem>
component depending on how you have that setup.您可能还需要在
<OverflowMenuItem>
组件上使用 onClick 属性,具体取决于您的设置方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.