[英]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. 我想在顶部绑定
updateHeroName
。 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. 并将2个param(hero_id和event)传递到
updateHeroName
但是我不知道如何传递event和一个名为_hero.id
的参数,因此代码无法正常工作。 Can I do this in javascript?? 我可以用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) 您可以像
onChange={ (event) => this.updateHeroName(_hero.id, event) }
(就像Alexander T建议的那样)
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. 但是通常,最好不要在
render
内部使用箭头函数或bind
方法,因为它会在任何render
调用上生成该函数的新副本。 Move function declaration to the class constructor
. 将函数声明移至
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 它不是ES2015规范的一部分,但babel stage-0预设支持此语法
You can read more about context binding in React in this article 您可以在本文中的React中阅读有关上下文绑定的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.