user2492364 user2492364 - 3 months ago 11
React JSX Question

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>
);
}
}

Answer

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>             
     );
   }
 }