Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从函数的React组件调用函数_Javascript_Reactjs - Fatal编程技术网

Javascript 从函数的React组件调用函数

Javascript 从函数的React组件调用函数,javascript,reactjs,Javascript,Reactjs,我有一个反应组件 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 (

我有一个反应组件

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>
    )
  }
}
导出函数sendAlert(msg){
showarert()//如何在普通函数中调用React.Component中的函数
}
导出类警报扩展React.Component{
showAlert=()=>{
警报(“a”)
};
render(){
返回(
组成部分
)
}
}
可以调用从React.Component调用函数的函数从技术上讲,您可以这样做,但您可能应该提取通用函数并从两个位置调用它

可以通过创建组件的实例来执行此操作:

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();
    };

    ...
    ...
}

只有当您的方法是静态方法时,才能这样做

您可以在类内声明方法,如下所示:

static showAlert() { alert("a"); }
然后您可以在外部以CLASSNAME.METHOD\u NAME的形式访问它

例如:
Alert.showAlert()


正如@Davin在他的回答中所说,您可以在外部声明它(这也是我的建议,更干净的代码),但是如果您必须在类内部声明它,您可以使用静态选项。

如果您的方法不使用
,您可以使用静态方法

import Alert from '../somewhere';

export function sendAlert(msg) {
    Alert.showAlert() // <<--- use Alert.method() to call a static method
}
从“../somewhere”导入警报;
导出函数sendAlert(msg){
Alert.showAlert()//
export class Alert extends React.Component {

// Make the method to static
static showAlert = () => {
   alert("a")
};

render() {
     return (
         <div>
             <h1>Component</h1>
         </div>
        )
     }
}