![](/img/trans.png)
[英]how to call the same function from two different places in angularjs
[英]How to call two onClick events from different places
我有一個按鈕將有一個硬編碼的 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();
在第一個 onClick 的renderPressedButton
內部,但它不起作用。 第二個 onClick( anotherClickHandler
) 被調用,但不是第一個 ( 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 功能和另一個功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.