简体   繁体   中英

How do I check if my event.target is typeof HTML input element in React?

Please see this minimum example https://codepen.io/rockmandash/pen/Rzwowd

The code is this:

在此处输入图片说明

<div class="cool">
  <input type="checkbox" value="checkbox1">
  <input type="checkbox" value="checkbox2">
  <input type="checkbox" value="checkbox3">
</div>
document.querySelector(".cool").addEventListener("click", event => {
  // In React World
  // How do I check if event.target is typeof HTML.input Element?
  console.log(event.target.value);
});

I'm asking this question because I have thousands of input elements, in react, I will have to create thousands callback function.

So I move my function up to their parent, but then I have to validate if I am current clicking an input element.

Otherwise, I could potentially set the wrong event.target.value.

if (event.target instanceof HTMLInputElement)

Use event type

handleCheck = (event) => {
  // In React World
  console.log(event.target.type);
}

<div class="cool">
  <input onClick={this.handleCheck} type="checkbox" value="checkbox1" />
  <input onClick={this.handleCheck} type="checkbox" value="checkbox2" />
  <input onClick={this.handleCheck} type="checkbox" value="checkbox3" />
</div>

DEMO

 <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 = { name: 'React' }; } handleCheck = (event) => { console.log(event.target.type); } render() { return ( <div> <div class="cool"> <input onClick={this.handleCheck} type="checkbox" value="checkbox1" /> <input onClick={this.handleCheck} type="checkbox" value="checkbox2" /> <input onClick={this.handleCheck} type="checkbox" value="checkbox3" /> <input onChange={this.handleCheck} type="text" /> </div> </div> ); } } ReactDOM.render( <App />, document.getElementById('root') ); </script>

This is a good example of event delegation. See How JavaScript Event Delegation Works .

To check the type of the clicked element use tagName or nodeName .

if (event.target.nodeName === "A")

Please notice you need to use upper case: DIV , LI , A ,...

Note: In your specific case you can check the type of your input element like so: event.target.type === "submit" . But elements like div , li , a don't have a type attribute so the value of event.target.type will be undefined for them all.

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