简体   繁体   中英

how js know which button is clicked?

I'm new to React. So when I create a new React app, for example, a component that render some buttons like

//index.html

<button class="m-2 btn btn-block btn-secondary">Creat</button>
<button class="m-2 btn btn-block btn-secondary">Save</button>
<button class="m-2 btn btn-block btn-secondary">Delete</button>

I know there is a bundle.js behind the scene, but for all the button html tags, there is no "id" attribute to differentiate each button, so when I click the "save" button, how does bundle.js know which button I have clicked?

There is a hidden event listeners that is registered to the DOM element. If you use Chrome development tools, you can inspect the button element and you will see in Event Listeners tab that there are part of code which listen to those click events.

There is a addEventListener method which can add event listener to DOM element. https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

Initially, the HTML body is empty, when React create elements through JavaScript, it have reference to those elements and thus can call addEventListener on those elements.

Here is an example of how the internal of React may work.

 var b1 = document.createElement("button"); var b1text = document.createTextNode("Create"); b1.appendChild(b1text); b1.addEventListener("click", function() { alert("Create"); }); var b2 = document.createElement("button"); var b2text = document.createTextNode("Delete"); b2.appendChild(b2text); b2.addEventListener("click", function() { alert("Delete"); }); var element = document.getElementById("root"); element.appendChild(b1); element.appendChild(b2);
 <div id="root"> </div>

The internal of React have reference to DOM object without having an id so it can add event listener through the reference.

The code you wrote as HTML in .jsx are actually not used as plain HTML, it is compiled into JavaScript. You can try to convert React JSX to React JS (which is in Bundle.js) here https://babeljs.io/repl/ .

This is how React sees your HTML code

React.createElement("div", null, React.createElement("button", {
  className: "m-2 btn btn-block btn-secondary"
}, "Creat"), React.createElement("button", {
  className: "m-2 btn btn-block btn-secondary"
}, "Save"), React.createElement("button", {
  className: "m-2 btn btn-block btn-secondary"
}, "Delete"));

Additional information can be found here https://reactjs.org/docs/jsx-in-depth.html

React uses virtual DOM, the code changes you make, changes the virtual DOM not the real one. When an event such as onclick happens or user typing into an input, React compares the state of the real DOM and virtual DOM, if they are the same nothing happens, if they are different React will update the real DOM to match the virtual DOM.

Add onclick listener to your buttons and pass an argument to the onclick function like below.

onButtonClick = (btn) => {
  console.log(btn)
}

<button onClick={() => this.onButtonClick('create')} class="m-2 btn btn-block btn-secondary">Creat</button>

 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script> <div id="root"></div> <script type="text/babel"> class App extends React.Component { constructor() { super(); this.state = { result: '', isLoading: false }; } onButtonClick = (btn) => { console.log(btn) } render() { return ( <div> <button onClick={() => this.onButtonClick('create')} class="m-2 btn btn-block btn-secondary">Creat</button> <button onClick={() => this.onButtonClick('save')} class="m-2 btn btn-block btn-secondary">Save</button> <button onClick={() => this.onButtonClick('delete')} class="m-2 btn btn-block btn-secondary">Delete</button> </div> ); } } ReactDOM.render( <App />, document.getElementById('root') ); </script>

Or add an id to the buttons

onButtonClick = (event) => {
    console.log(event.target.id) // get the id of the clicked button
}

<button id="1" onClick={this.onButtonClick} class="m-2 btn btn-block btn-secondary">Creat</button>

 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script> <div id="root"></div> <script type="text/babel"> class App extends React.Component { constructor() { super(); this.state = { result: '', isLoading: false }; } onButtonClick = (event) => { console.log(event.target.id) } render() { return ( <div> <button id="1" onClick={this.onButtonClick} class="m-2 btn btn-block btn-secondary">Creat</button> <button id="2" onClick={this.onButtonClick} class="m-2 btn btn-block btn-secondary">Save</button> <button id="3" onClick={this.onButtonClick} class="m-2 btn btn-block btn-secondary">Delete</button> </div> ); } } ReactDOM.render( <App />, document.getElementById('root') ); </script>

Each of your buttons will need to be connected to some kind of action using onClick or onSubmit (if in a form). Here's an example of an alert box that fires a mutation function to delete an item if the viewer presses ok...

  <button class="m-2 btn btn-block btn-secondary" onClick={e => {
    if (window.confirm("Are you sure you wish to delete this?"))
      onSubmit(e, removeTagFromDeck);
     }}>Delete</button>

If you need id's to further refine your CSS, you can simply add id='whatever' to the 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