我创建了一个可以在其他页面上重复使用的按钮组件
import styled from 'styled-components'
const Button = styled.button`
background: #0070f3;
border-radius: 5px;
position: relative;
display: inline-block;
line-height: normal;
font-family: inherit;
font-size: inherit;
color: #FFF;
font-weight: 500;
text-decoration: none;
padding: 10px 20px;
transition: 0.3s all ease;
outline: 0;
border: 0;
cursor: pointer;
`
export const ButtonComponent = ({ children, className }) => {
return (
<Button className={className}>{children}</Button>
)
}
但我想给每个 Button 组件一个不同的 onClick 链接。我该怎么做?
答案 0 :(得分:4)
您可以将 onClick
事件作为道具传递给您的公共组件,并且在该 onClick
道具中,您可以传递您希望在点击该按钮时执行的不同功能/事件
import styled from 'styled-components'
const Button = styled.button`
background: #0070f3;
border-radius: 5px;
position: relative;
display: inline-block;
line-height: normal;
font-family: inherit;
font-size: inherit;
color: #FFF;
font-weight: 500;
text-decoration: none;
padding: 10px 20px;
transition: 0.3s all ease;
outline: 0;
border: 0;
cursor: pointer;
`
export const ButtonComponent = ({ children, className, onClick }) => {
return (
<Button className={className} onClick={onClick}>{children}</Button>
)
}
答案 1 :(得分:1)
你可以给按钮另一个参数,在那里你给他一个函数的引用,像这样:
import styled from 'styled-components'
const Button = styled.button`
background: #0070f3;
border-radius: 5px;
position: relative;
display: inline-block;
line-height: normal;
font-family: inherit;
font-size: inherit;
color: #FFF;
font-weight: 500;
text-decoration: none;
padding: 10px 20px;
transition: 0.3s all ease;
outline: 0;
border: 0;
cursor: pointer;
`
export const ButtonComponent = ({ children, className, myFunction }) => {
return (
<Button className={className} onClick={myFunction}>{children}</Button>
)
}
答案 2 :(得分:1)
只需将 onClick 功能作为按钮中的道具
export const ButtonComponent = ({ children, className, onClick }) => {
return (
<Button className={className} onClick={onClick}>{children}</Button>
)
}
答案 3 :(得分:0)
你也可以像这样将 props 传递给子组件。这样,您可以直接将其他事件传递给组件(https://reactjs.org/docs/events.html)或针对特定用例覆盖其他一些道具等。
export const ButtonComponent = ({ children, className, ...props }) => {
return (
<Button {...props} className={className}>{children}</Button>
)
}
在父级中,您可以这样称呼它。
<ButtonComponent onClick={() => alert('Hello')}>Click me</ButtonComponent>