我有一个可重用的‘按钮’组件,我想在其中一个中插入一条路由到另一个页面,我试着将<Link> </Link>放到另一个页面,但是它需要我的CSS,并且按钮很小。如果我只是把它放在文本上就行了,但是如果只点击文本就能把它带到另一页,那就太糟糕了;
组件按钮
import React from 'react';
type ButtonProps = {
style: React.CSSProperties;
children: React.ReactNode;
};
function MouseOver(event: any) {
event.target.style.opacity = '90%'
}
function MouseOut(event: any) {
event.target.style.opacity = ''
}
function Button({ style, children }: ButtonProps) {
return (
<button
onMouseOver={MouseOver}
onMouseOut={MouseOut}
style={style}
>
{children}
</button>
)
}
export default Button;重用
<Button
key={id}
style={{
backgroundColor: 'green',
color: 'white',
fontSize: '1.6rem',
borderRadius: '4px',
border: 'none',
display: 'block',
padding: '1rem',
cursor: 'pointer',
fontFamily: '"Roboto", sans-serif',
transition: 'all 0.3s'
}}
>
Create your account
</Button>发布于 2022-09-13 18:31:39
您可以用<Link>包装按钮,并用道具传递href:
function Button({ style, children, href }) {
return (
<Link href={href}>
<button
onMouseOver={MouseOver}
onMouseOut={MouseOut}
style={style}
>
{children}
</button>
</Link>
)
}我会将其抽象为<ButtonLink>组件,如:
function ButtonLink({ style, children, href}) {
return (
<Link href={href}>
<Button>
{children}
</Button>
</Link>
)
}或者,您可以在按钮上实现一个onClick并在那里执行路由。
function Button({ style, children, href }) {
const clickHandler = (e) => {
// your redirection logic here (example with history api):
history.push("/some/url")
}
return (
<button
onMouseOver={MouseOver}
onMouseOut={MouseOut}
onClick={clickHandler}
style={style}
>
{children}
</button>
)
}这里的实现实际上取决于用于路由/重定向的API。在您的示例中,您的<Link>组件听起来像是一个实际的html <a>标记,因为它正在改变子组件的样式。确保您正在使用来自路由器库的链接组件(例如。路由器https://v5.reactrouter.com/web/api/Link)
PS:在函数组件的功能体中定义方法是很好的实践,而不是在它们的外部定义方法(参见最后一个示例)。
发布于 2022-09-13 18:27:48
链接可能太残忍了。它有href="“属性吗?你试过玩这个吗?我想我通常会用href来创建按钮,它们不会将链接限制在文本上。
https://stackoverflow.com/questions/73707507
复制相似问题