我有一个按钮,它将有一个硬编码的 onClick,而另一个使用该组件的按钮可以创建他的自定义 onClick。我不认为这是重复的,因为我找到的所有问题都建议以硬编码方式使用 onClick,这在使用 Button 组件时无法更改。
这个组件:
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 onClickHandler = () => {
renderPressedButton();
onClick();
}
使用该组件我将拥有自定义的 onClick
const anotherClickHandler = () => {
console.log('Hey, this is a function outside Button component');
}
<Button onClick={anotherClickHandler}>Button</Button>
我尝试过从第一个 onClick 调用 renderPressedButton
内的 onClick();
但它不起作用。第二个 onClick(anotherClickHandler
) 被调用,但第一个 onClick(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}
/>
);
};
使用按钮时:
<Button onClick={justASimpleOnClickHandler}>Toggle</Button>
这样我就可以在使用我的组件时拥有我的主要 onClick 函数和另一个函数。
关于javascript - 如何从不同地方调用两个onClick事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59078984/