javascript - 从函数中调用 React 组件的函数

标签 javascript reactjs

我有一个 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/

相关文章:

javascript - 如何获取 obj 值和键来为 POST 方法构建数组对象

reactjs - 没有 Redux 的快速变化的状态

javascript - 如何在回调中访问正确的“this”?

javascript - 通过表单在 Flask 上发布数据会出现 400 Bad Request

javascript - 悬停时显示前一个元素

javascript - 在处理更改时通过状态 react 传递值

javascript - 混合错误 : This request has been blocked; the content must be served over HTTPS

javascript - React,三元条件下的 Div 不呈现

javascript - react Hook : Can't update state inside function component

css - React 元素中无法识别 minmax CSS 函数