如何从普通的Javascript函数调用ReactJS类组件和功能组件?

时间:2019-10-30 09:18:47

标签: javascript reactjs

我想从普通的JavaScript函数调用ReactJS函数(function Component)。它不打印输出,因为ReactJS使用JSX语法。是否可以从常规JS功能调用ReactJS功能组件?我的示例代码在这里:

class Extra extends React.Component { 
      //This is the ReactJS class component 
}

function Greeting() {
       // This is the ReactJS functional component
      // I wanted to call this ReactJS functional component from the 
      normal JavaScript function 

      return (<Extra/>);
}

function Calling() {
    // This  is normal JavaScript function  which I have defined in the 
     separate file. From this function I wanted to call the ReactJS 
     function.

     Greeting();
}

我尝试过了。我从普通的JS函数中调用了ReactJS功能组件。它位于ReactJS函数内部,但未在浏览器上显示JSX代码(ReactJS类组件的JSX语法)

预先感谢

2 个答案:

答案 0 :(得分:0)

是的,您可以从普通的javascript函数调用Component类函数,但是您需要使React函数成为 static ,然后通过className.react_function()从noraml javascript进行调用

答案 1 :(得分:0)

class Extra extends React.Component { 
  //This is the ReactJS class component 

  static Greeting=()=>{
    console.log("Greeting from react class function");
  }
}


function Calling() {
  // This  is normal JavaScript function  which I have defined in the  separate file.From this function I wanted to call the ReactJS function.
 Extra.Greeting();
}