【问题标题】:How do I call ReactJS class component and functional component from normal Javascript function?如何从普通的 Javascript 函数中调用 ReactJS 类组件和功能组件?
【发布时间】:2020-02-25 13:19:11
【问题描述】:

我想从普通的 JavaScript 函数中调用一个 ReactJS 函数(函数式组件)。它不打印输出,因为 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 语法)

提前致谢

【问题讨论】:

  • 请提及代码理解问题
  • edit your question 而不是在 cmets 中发布代码。很难阅读。也请使用它周围的`标签将其格式化为代码。
  • 我现在已经发布了代码。所以,请通过它。

标签: javascript reactjs


【解决方案1】:

是的,您可以从普通的 javascript 函数调用组件类函数,但您需要将该反应函数 static 然后通过 className.react_function() 从 noraml javascript 调用

【讨论】:

  • 你能给我举个例子吗?我是这个 ReactJS 和 JavaScript 的新手,所以我没有让你清楚。你能拿我上面的例子给我看看吗?
【解决方案2】:
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();
}

【讨论】:

  • 如果你想从单独的文件中调用,你必须在这个单独的文件中包含那个“额外的”反应类,比如 import Extend from '{path_to_that_file}';
  • 看看我的调用函数序列是..我想从 React 功能组件( Greeting() )调用我的 React Class 组件(Extra)所以,我的 React 组件应该在 Class 组件之外然后在我必须从普通的 JavaScript 函数中调用这个 React 函数组件之后。
  • 按我说的应该叫我
  • 谢谢。我会试试的:)
猜你喜欢
  • 2021-03-22
  • 2021-08-27
  • 1970-01-01
  • 2021-08-16
  • 1970-01-01
  • 2022-11-16
  • 1970-01-01
  • 2020-12-04
  • 1970-01-01
相关资源
最近更新 更多