如何在onChange事件处理器中调用两个函数?附代码求助
Hey there! Let's get your two functions firing properly in the onChange event. I took a look at your code, and there's a small but crucial issue keeping this from working: you're referencing this.onChange but not actually calling it, plus you need to pass the event object to it since your method relies on e.
Here's the breakdown of the fix:
- You need to invoke
this.onChangewith parentheses and pass the evente(since youronChangemethod usese.target.value). - Keep the order of calls as you need—first
handleValueChanges, then your validation/setState method.
Option 1: Call both functions directly in the arrow function
Update your input's onChange prop like this:
<input type="text" size="3" defaultValue={ViewHelpers.toFixed(val1, 2)} onChange={(e) => { this.handleValueChanges(this.props.valCols[i]); this.onChange(e); // Fixed: call the function and pass the event }} />
Option 2: Create a dedicated handler method (cleaner for complex logic)
If you want to keep your JSX cleaner, wrap both calls in a separate class method:
// Add this method to your component handleInputUpdate = (e) => { this.handleValueChanges(this.props.valCols[i]); this.onChange(e); } // Then use it in your input <input type="text" size="3" defaultValue={ViewHelpers.toFixed(val1, 2)} onChange={this.handleInputUpdate} />
Quick note:
Double-check that this.props.valCols[i] is the correct value you want to pass to handleValueChanges. If you're rendering this input inside a loop (like map), make sure i is properly scoped to avoid unexpected values (using let in the loop or passing the value directly instead of relying on i can help here).
内容的提问来源于stack exchange,提问作者My Test

