简体   繁体   中英

onClick fires multiple time in React.js

I have following component.

import React from 'react'
import Profile from './Profile'

import Messages from './Messages'
class ContactContent extends React.Component {
  constructor () {
    super()
    this.state = {
      message: ''
    }
    this.handleOnClick = (e) => {
      e.preventDefault()
      console.log('send message called')
    //   this.props.onSendMessage(this.state.message)
    }
  }

  render () {
    const { id, name, profile, messages } = this.props.user
    return (
      <div className='content'>
        <Profile
          name={id}
          profile={profile}
        />
        <Messages
          messages={messages}
        />
        <div className='message-input'>
          <div className='wrap'>
            <input type='text' placeholder='Write your message...' onChange={(e) => this.setState({ message: e.target.value })} />
            {/* <i className="fa fa-paperclip attachment" aria-hidden="true"></i> */}
            <button className='' onClick={this.handleOnClick}><i className='fa fa-paper-plane' aria-hidden='true' /></button>
          </div>
        </div>
      </div>
    )
  }
}

export default ContactContent

when I click on button onclick is called which triggers handleonclick function. but handleonclick is being called like infinit time. this is a weird behavior I have seen this first time any idea what I have done wrong?

Fixed it there was an external javascript file which was creating this issue. Nothing is wrong with the code.

No, you are calling the handleOnClick each time on page load/render load here So without making this, or to avoid multiple call try to use:

fat arrow call of that function on onClick event.

<button className='' onClick={(e) => this.handleOnClick(e)}><i className='fa fa-paper-plane' aria-hidden='true' /></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