简体   繁体   English

js如何知道点击了哪个按钮?

[英]how js know which button is clicked?

I'm new to React.我是 React 的新手。 So when I create a new React app, for example, a component that render some buttons like因此,当我创建一个新的 React 应用程序时,例如,一个呈现一些按钮的组件

//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?我知道幕后有一个bundle.js,但是对于所有按钮html标签,没有“id”属性来区分每个按钮,所以当我点击“保存”按钮时,bundle.js如何知道是哪个按钮我点击了吗?

There is a hidden event listeners that is registered to the DOM element.有一个注册到 DOM 元素的隐藏事件侦听器。 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.如果你使用 Chrome 开发工具,你可以检查按钮元素,你会在Event Listeners选项卡中看到有部分代码监听这些点击事件。

There is a addEventListener method which can add event listener to DOM element.有一个addEventListener方法可以将事件监听器添加到 DOM 元素。 https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener 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.最初,HTML 主体是空的,当 React 通过 JavaScript 创建元素时,它引用了这些元素,因此可以在这些元素上调用addEventListener

Here is an example of how the internal of React may work.这是 React 内部如何工作的示例。

 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. React 内部引用了没有 id 的 DOM 对象,因此它可以通过引用添加事件监听器。

The code you wrote as HTML in .jsx are actually not used as plain HTML, it is compiled into JavaScript.您在.jsx中作为 HTML 编写的代码实际上并没有用作纯 HTML,而是被编译成 JavaScript。 You can try to convert React JSX to React JS (which is in Bundle.js) here https://babeljs.io/repl/ .你可以在这里https://babeljs.io/repl/尝试将 React JSX 转换为 React JS(在 Bundle.js 中)。

This is how React sees your HTML code这就是 React 看到你的 HTML 代码的方式

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可以在此处找到其他信息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. React 使用虚拟 DOM,你所做的代码更改,更改的是虚拟 DOM 而不是真实的 DOM。 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.当诸如 onclick 之类的事件发生或用户输入输入时,React 会比较真实 DOM 和虚拟 DOM 的状态,如果它们相同则什么也不会发生,如果它们不同 React 将更新真实 DOM 以匹配虚拟 DOM。

Add onclick listener to your buttons and pass an argument to the onclick function like below.将 onclick 侦听器添加到您的按钮并将参数传递给 onclick 函数,如下所示。

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或者给按钮添加一个id

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).您的每个按钮都需要使用 onClick 或 onSubmit(如果在表单中)连接到某种操作。 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.如果您需要 id 来进一步完善您的 CSS,您只需将 id='whatever' 添加到按钮即可。

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

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