我有一个 React 组件
export function sendAlert(msg) {
showAlert() //How to call in normal function a function from React.Component
}
export class Alert extends React.Component {
showAlert = () => {
alert("a")
};
render() {
return (
<div>
<h1>Component</h1>
</div>
)
}
}
可以调用从React.Component
调用函数的函数
最佳答案
从技术上讲,您可以做到这一点,但您可能应该提取公共(public)函数并从两个地方调用它。
您可以通过创建组件的实例来实现:
export function sendAlert(msg) {
const alert = new Alert();
alert.showAlert()
}
但是,您应该提取代码:
function commonShowAlert() {
alert("a");
}
export function sendAlert(msg) {
commonShowAlert();
}
export class Alert extends React.Component {
showAlert = () => {
commonShowAlert();
};
...
...
}
关于javascript - 从函数中调用 React 组件的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46912202/