我有一個可重用的“按鈕”組件,我想在其中一個中插入一條路由以轉到另一個頁面,我嘗試放置<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>
uj5u.com熱心網友回復:
您可以使用 a 包裹您的按鈕<Link>并使用 prop 傳遞 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>標記,因為它正在改變子項的樣式。確保您使用的是路由器庫中的鏈接組件(例如 react-router https://v5.reactrouter.com/web/api/Link)
PS:最好在函陣列件的函式體中定義方法,而不是在它們之外(參見最后一個示例)。
uj5u.com熱心網友回復:
林克可以這么殘忍。它有 href="" 屬性嗎?你試過玩這個嗎?我想我通常會創建帶有 href 的按鈕,并且它們不會將鏈接限制為文本。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/507074.html
標籤:javascript 反应 打字稿
下一篇:從其css屬性訪問div
