Javascript 在 onChange 事件中调用 2 个函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35435611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:43:07  来源:igfitidea点击:

Call 2 functions within onChange event

javascriptreactjs

提问by Ilja

I'm a bit stuck with my component, I need to call onChange from props so

我的组件有点卡住了,我需要从 props 调用 onChange 所以

<input type="text" value={this.state.text} onChange={this.props.onChange} />

but also call another function within the component called handleChange()that updates the state.text, I tried

但也调用组件中的另一个函数handleChange()来更新 state.text,我试过了

 <input type="text" value={this.state.text} onChange={this.props.onChange; this.handleChange} />

but this doesn't seem to work.

但这似乎不起作用。

回答by diiN__________

You can do it by putting the two functions in double quotes:

您可以通过将两个函数放在双引号中来实现:

<input type="text" value={this.state.text} onChange="this.props.onChange(); this.handleChange();" />

This should work. But it would be better if you call the second function within the first one:

这应该有效。但是如果你在第一个函数中调用第二个函数会更好:

function testFunction() {
    onChange();
    handleChange();
}

回答by Carl Vitullo

function(e) {this.props.onChange(e); this.handleChange(e)}.bind(this)

function(e) {this.props.onChange(e); this.handleChange(e)}.bind(this)

You might not need .bind(this), but I suspect you will.

你可能不需要.bind(this),但我怀疑你会。

This will create a new function on each render, so it'd be better in certain respects to have that function be a component method, but this should work.

这将在每次渲染时创建一个新函数,因此在某些方面最好将该函数作为组件方法,但这应该可行。

回答by Julia Stanina

If you want inline solution, you can do something like this:

如果您想要内联解决方案,您可以执行以下操作:

 <input type="text" value={this.state.text} onInput={this.props.onChange} onChange={this.props.handleChange} />

Difference between onInput and onChage is here:

onInput 和 onChage 之间的区别在这里:

Difference between "change" and "input" event for an `input` element

`input` 元素的“更改”和“输入”事件之间的区别