简体   繁体   中英

Can I send event and a param to a function?

Here is my code :

export default class HeroDetail extends Component {
constructor(props) {
   super(props);
 }

 updateHeroName(event) {
     this.props.actions.changeName(this.props.heroAppState.selectedHero.id, event.target.value);
 }
 render() {
   const _hero = this.props.heroAppState.selectedHero;
     return (
           <div>
             <input placeholder="name"
               value={_hero.name}
               onChange={this.updateHeroName.bind(this)} />
            </div>             
     );
   }
 } 

I want to bind updateHeroName at the top. And pass 2 param(hero_id and event) into updateHeroName But I don't know how to pass event and a param named _hero.id , So the code not work. Can I do this in javascript??

// Fail code 
export default class HeroDetail extends Component {
constructor(props) {
   super(props);
   this.updateHeroName = this.updateHeroName.bind(this);
 }

 updateHeroName(hero_id, event) {
     this.props.actions.changeName(hero_id, event.target.value);
 }
 render() {
   const _hero = this.props.heroAppState.selectedHero;
     return (
           <div>
             <input placeholder="name"
               value={_hero.name}
               onChange={this.updateHeroName(_hero.id, event)} />
            </div>             
     );
   }
 } 

This should work:

export default class HeroDetail extends Component {
constructor(props) {
   super(props);
   this.updateHeroName = this.updateHeroName.bind(this);
 }

 updateHeroName(hero_id, event) {
     this.props.actions.changeName(hero_id, event.target.value);
 }
 render() {
   const _hero = this.props.heroAppState.selectedHero;
     return (
           <div>
             <input placeholder="name"
               value={_hero.name}
               onChange={(event) => this.updateHeroName(_hero.id, event)} />
            </div>             
     );
   }
 } 

You can do like onChange={ (event) => this.updateHeroName(‌​_hero.id, event) } (as Alexander T suggested)

But generally, it's better not to use arrow functions or bind methods inside render as it generates a new copy of the function on any render call. Move function declaration to the class constructor .

I personally prefer to use arrow functions as class properties in this case

class MyClass extends React.Component {

  handleClick = () => {
    // your logic
  };

  render() {
    return (
      <button onClick={this.handleClick}>Click me</button>
    );
  }
}

It's not a part of ES2015 specification but babel stage-0 preset supports this syntax

You can read more about context binding in React in this article

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