简体   繁体   中英

Onclick event handler with passing this in reactjs

My component is as below:

import React, {PropTypes} from 'react';
export default class Viewdesc extends React.Component {
render() {
return (
    <div className="col-md-12 slide-row">
        <div className="col-md-12 overview-about-property">
            <div className="expandabletext less">
                <div className="col-md-12" dangerouslySetInnerHTML={{__html: this.props.record.ABOUT}}></div>
            </div>
            <div className="showmore"> Show More </div>
        </div>
    </div>
);
}
}

I want to call function say showmorefunct() passing clicked handler like this in jquery. How can I do this?

You can bind you function and pass params which you want, if you want to. You can do something like :

class Test extends React.Component {
    handleClick(param, e){
        console.log(e);
        console.log(param);
    }

    render(){
        return (
        <div className="showmore" onClick={this.handleClick.bind(this, "Some param if you need it")}> Show More </div>
      )
    }
}

React.render(<Test />, document.getElementById('container'));

Here is fiddle .

UPDATE http://jsfiddle.net/jwm6k66c/1517/

I don't quite really understand your question, but I imagine you want this-

import React, {PropTypes} from 'react';
export default class Viewdesc extends React.Component {
  constructor(props) {
    super(props)
    this.showMoreFunct = this.showMoreFunct.bind(this)
  }
  showMoreFunct() {
    alert('Show more clicked!')
  }
  render() {
    return (
      <div className="col-md-12 slide-row">
        <div className="col-md-12 overview-about-property">
            <div className="expandabletext less">
              <div className="col-md-12" dangerouslySetInnerHTML={{__html: this.props.record.ABOUT}}></div>
              </div>
            <div className="showmore"> <span onClick={this.showMoreFunct}>Show More</span> </div>
        </div>
      </div>
    );
  }
}

You can replace span with a or button . You just need to specify the function you want to call to onClick prop. React will call it automatically when the user clicks on that span .

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