onClick 响应组件
onClick React component
基本上我创建了一个看起来像这样的按钮组件:
import React from "react";
import styles from "./button.module.scss";
const Button = ({ icon, text, align, bgcolor }) => {
const btnStyle = {
justifySelf: align,
};
return (
<>
<div className={"btn " + bgcolor} style={btnStyle}>
<i className={icon}></i> {text}
</div>
</>
);
};
export default Button;
在我的应用程序中,我可以通过以下方式调用它:
<Button
icon="fa-light fa-trash"
text="Some text"
align="end"
bgcolor="yellow"
></Button>
但是,同时我希望有一个类似的onclick事件:
<div onClick={() => setState(!state)}>Click me</div>
如何实现?
编写一个可以作为 props 传递给 Button 组件的函数:
const function=()=>{
setState(!state)
}
<Button
icon="fa-light fa-trash"
text="Some text"
align="end"
bgcolor="yellow"
function={function}
></Button>
然后像这样在里面使用它:
const Button = ({ icon, text, align, bgcolor, function }) => {
const btnStyle = {
justifySelf: align,
};
return (
<>
<div onClick={function} className={"btn " + bgcolor} style={btnStyle}>
<i className={icon}></i> {text}
</div>
</>
);
};
基本上我创建了一个看起来像这样的按钮组件:
import React from "react";
import styles from "./button.module.scss";
const Button = ({ icon, text, align, bgcolor }) => {
const btnStyle = {
justifySelf: align,
};
return (
<>
<div className={"btn " + bgcolor} style={btnStyle}>
<i className={icon}></i> {text}
</div>
</>
);
};
export default Button;
在我的应用程序中,我可以通过以下方式调用它:
<Button
icon="fa-light fa-trash"
text="Some text"
align="end"
bgcolor="yellow"
></Button>
但是,同时我希望有一个类似的onclick事件:
<div onClick={() => setState(!state)}>Click me</div>
如何实现?
编写一个可以作为 props 传递给 Button 组件的函数:
const function=()=>{
setState(!state)
}
<Button
icon="fa-light fa-trash"
text="Some text"
align="end"
bgcolor="yellow"
function={function}
></Button>
然后像这样在里面使用它:
const Button = ({ icon, text, align, bgcolor, function }) => {
const btnStyle = {
justifySelf: align,
};
return (
<>
<div onClick={function} className={"btn " + bgcolor} style={btnStyle}>
<i className={icon}></i> {text}
</div>
</>
);
};