龙空技术网

七爪源码:如何在 React 中使用按钮作为链接

庄志炎 102

前言:

此刻咱们对“htmlbutton链接”可能比较看重,看官们都需要剖析一些“htmlbutton链接”的相关知识。那么小编在网摘上搜集了一些关于“htmlbutton链接””的相关文章,希望大家能喜欢,咱们一起来了解一下吧!

了解如何创建一个按钮链接,使浏览器在单击时导航到新的 URL。

HTML 锚元素

要将按钮用作 React 中的链接,请将按钮包装在锚 (<a>) 元素中。 单击链接按钮将使浏览器导航到指定的 URL。

export default function MyComponent() {  return (    <div>      {/* Anchor link */}      <a href="/posts">        <button>Posts</button>      </a>    </div>  );}

react-router-dom 链接组件

如果您使用的是 React Router,则将按钮包装在 Link 组件中,以使浏览器导航到指定的路由,而无需在单击按钮时刷新页面。

import { Link } from 'react-router-dom';export default function MyComponent() {  return (    <div>      <Link to="/posts">        <button>Posts</button>      </Link>    </div>  );}

react-router-dom Link 组件渲染一个锚元素,因此它的工作方式与第一个示例类似。

我们还可以通过使用锚元素或链接组件包装自定义按钮组件作为链接。 例如:

import { Link } from 'react-router-dom';function MyCustomButton({ children }) {  return <button>{children}</button>;}export default function MyComponent() {  return (    <div>      <Link to="/posts">        <MyCustomButton>Posts</MyCustomButton>      </Link>    </div>  );}

使用 Material UI 按钮作为链接

使用 Material UI 时,我们可以使用 href 属性为 Button 组件指定一个链接。

import { Button } from '@mui/material';export default function MyComponent() {  return (    <div>      <Button href="/posts">Posts</Button>    </div>  );}

Material UI 组件 Pro

要用作 React Router Link,我们可以使用 Button 的 component 属性。

import { Button } from '@mui/material';import { Link } from 'react-router-dom';export default function MyComponent() {  return (    <div>      <Button component={Link} to="/posts">        Posts      </Button>    </div>  );}

其他 Material UI 组件(如 IconButton)也有一个组件属性。 当我们希望按钮组件从其父组件继承其颜色时,设置此属性很有用。

在这种情况下,如果我们用 Link 包装组件,它将从 Link 而不是预期的父级继承其颜色。 例如:

import { IconButton, Box, Typography } from '@mui/material';import { Link } from 'react-router-dom';import { Photo } from '@mui/icons-material';export default function MyComponent() {  return (    // We want the IconButton to inherit its parent color (white)    <Box sx={{ backgroundColor: 'black', color: 'white', padding: 2 }}>      <Typography>Lorem Ipsum</Typography>      {/* But this wrapping makes it inherit from this Link */}      <Link to="/photos">        <IconButton color="inherit">          <Photo />        </IconButton>      </Link>    </Box>  );}

我们可以通过将组件属性设置为 Link 而不是包装来解决此问题:

import { IconButton, Box, Typography } from '@mui/material';import { Link } from 'react-router-dom';import { Photo } from '@mui/icons-material';export default function MyComponent() {  return (    <Box sx={{ backgroundColor: 'black', color: 'white', padding: 2 }}>      <Typography>Lorem Ipsum</Typography>      {/* Setting the "component" prop to a "Link" component */}      <IconButton component={Link} to="/photos" color="inherit">        <Photo />      </IconButton>    </Box>  );}

关注七爪网,获取更多APP/小程序/网站源码资源!

标签: #htmlbutton链接