简体   繁体   中英

how to import function in reactjs

AppFunction.js

export default function myFunction() {
  var str1 = "Hello ";
  var str2 = "world!";
  var res = str1.concat(str2);
  document.getElementById("demo").innerHTML = res;
}

App.js

import React, { Component } from 'react';
import myFunction  from './AppFunction';

class App extends Component {           
  render() {
    return (
      <div className="App">
        <button onclick="myFunction()">Try it</button>
        <p id="demo"></p>
      </div>
    );
  }
}

export default App;

I should to import an existing JavaScript library and then call it's functions.

componentDidMount() {
  myFunction()
}

When I write like this, working. But shows on screen without clicking the onclick button. I want to press the button and show it on the screen.

Change

<button onclick="myFunction()">Try it</button>

to

<button onClick={myFunction}>Try it</button>

You should use

export default function myFunction() {
  var str1 = "Hello ";
  var str2 = "world!";
  var res = str1.concat(str2);
  return res;
}

and

<button onClick={myFunction}>Try it</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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