简体   繁体   English

如何在 JSX 中添加函数?

[英]How to add function in JSX?

How do I add a JavaScript function in React, is this possible?如何在 React 中添加 JavaScript 函数,这可能吗? I get 'function is not valid'....我得到'功能无效'....

//Main component 
function Main () {

const vanilla_JS = function() { console.log('testing')}

 return (
  <main>
   <div>{vanilla_JS}</div>
  </main>

 )
}

ReactDOM.render(<Main />, document.getElementById('root');

1) You're missing a closing bracket on the ReactDOM line: 1) 您在ReactDOM行上缺少一个ReactDOM括号:

ReactDOM.render(<Main />, document.getElementById('root'));

2) You need to call the function for it to work 2)您需要调用该函数才能使其工作

vanilla_JS()

In this working example instead of logging to the console I'm returning a string:在这个工作示例中,我没有登录到控制台,而是返回一个字符串:

 function Main() { const vanilla_JS = function() { return 'testing'; } return ( <main> <div>{vanilla_JS()}</div> </main> ); } ReactDOM.render(<Main />, document.getElementById('root'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM