Javascript 如何从不同的位置调用两个onClick事件
我有一个按钮,它将有一个硬编码的onClick,另一个使用组件的按钮,可以创建自定义onClick。我不相信这是重复的,因为我能找到的所有问题都建议以硬编码的方式使用两个onClick,这在使用按钮组件时是无法更改的 该组件包括:Javascript 如何从不同的位置调用两个onClick事件,javascript,reactjs,Javascript,Reactjs,我有一个按钮,它将有一个硬编码的onClick,另一个使用组件的按钮,可以创建自定义onClick。我不相信这是重复的,因为我能找到的所有问题都建议以硬编码的方式使用两个onClick,这在使用按钮组件时是无法更改的 该组件包括: const Button = props => { const { children, toggle, ...other } = props; const [pressed, setPressed] = useState(true); const r
const Button = props => {
const { children, toggle, ...other } = props;
const [pressed, setPressed] = useState(true);
const renderPressedButton = e => {
setPressed(!pressed);
onClick(); //here onClick should be called
};
return (
<StyledButton
toggle={toggle}
pressed={toggle ? pressed : null}
onClick={toggle && renderPressedButton}
{...other}>
{children}
</StyledButton>
);
};
使用这个组件,我可以自定义onClick
const anotherClickHandler = () => {
console.log('Hey, this is a function outside Button component');
}
<Button onClick={anotherClickHandler}>Button</Button>
const另一个ClickHandler=()=>{
log('嘿,这是按钮组件之外的一个函数');
}
按钮
我尝试调用onClick()第一次单击时,renderPressedButton
内的code>,但它不起作用。调用第二个onClick(另一个clickHandler
),但不调用第一个(renderPressedButton
)
我做错了什么?我找到了解决办法
在主按钮上:
const Button = props => {
const { onClick } = props; //first i add onClick as a prop
const [pressed, setPressed] = useState(true);
const renderPressedButton = () => {
setPressed(!pressed);
if (onClick) {//then i check, if theres an onClick, execute it
onClick();
}
};
return (
<StyledButton
pressed={pressed}
{...props}
onClick={renderPressedButton}
/>
);
};
const按钮=道具=>{
const{onClick}=props;//首先我将onClick添加为一个prop
const[pressed,setPressed]=使用状态(true);
常量renderPressedButton=()=>{
setPressed(!pressed);
如果(onClick){//那么我检查,如果有onClick,执行它
onClick();
}
};
返回(
);
};
使用按钮时:
<Button onClick={justASimpleOnClickHandler}>Toggle</Button>
切换
这样,在使用我的组件时,我可以拥有我的主onClick函数和另一个onClick函数
<Button onClick={justASimpleOnClickHandler}>Toggle</Button>