简体   繁体   中英

How to have javascript inside of react.js

I am building a React.JS website and I am not entirely sure how to implement a section of JavaScript inside of my html. In normal HTML you would put the script inside of these tags:

<Script></Script>

But with react.js

function App() {
  return (
    <div>
        <button onlick='log()'>Log</button>
        <script>
            Log() = Console.log('Hello')
        </Script>
    </div>
  );
}

export default App;

Something like this will not work. How am i able to run a script this way?

Please learn how React works and how events work specifically

A basic example:

function App() {
  const log = () => console.log('Hello')

  return <button onClick={log}>Log</button>
}

export default App;

try this

 function App() {
const log =()=> {console.log('Hello')}
  return (
    <div>
        <button onClick={()=>log()}>Log</button>
     
    </div>
  );
}

export default App;

more information: https://reactjs.org/docs/handling-events.html

ReactJs Docs will be your friend here but basically you can run your javascript code inside your function component before your return statement

Here is a codesandbox link example

no need to use script tag you can put all the functions you want inside the App function and before return please specify what you need to do exactly so i can help

This is a better approach, but there's a lot you have to learn about React from your code in your question, beyond what I think I can explain in this answer. Your code has a number of typos and you probably do not actually need to use a <script> tag.

const logger = () => {
  console.log('hello')
}

function App() {
    return (
      <div>
          <button onClick={logger}>Log</button>
      </div>
    );
}

export default App;

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