I'm writing an extended version of the input element. Here is a simplified version of it:
我正在编写输入元素的扩展版本。这是它的简化版本:
var MyInput = React.createClass({
render: function () {
return (
<div>
<input type="text" onChange={this.changeHandler} {...this.props} />
</div>
);
},
changeHandler: function(event){
console.log('Trigger me first');
}
});
I'm using it in a context like this:
我在这样的上下文中使用它:
<MyInput placeholder="Test" value={this.state.myValue} onChange={function(event){
console.log('Trigger me second');
}} />
As you are probably suspecting one onChange
overrides the other depending on the order of the attributes.
你可能怀疑一个onChange会覆盖另一个,具体取决于属性的顺序。
With that in mind, what do you think would be the cleanest way to implement support for multiple event handlers for the same event, for the same element in cases like this one?
考虑到这一点,您认为对于同一事件实现对多个事件处理程序的支持的最简洁方法是什么,对于像这样的情况中的相同元素?
Edit
I was able to swap
onChange
and
{...this.props}
in the component and use
changeHandler: function(event)
{
console.log('input_changeHandler change');
this.props.onChange(event);
}
But I'm concerned if it's safe.
但我担心它是否安全。
1 个解决方案
#1
From the docs here https://facebook.github.io/react/docs/jsx-spread.html
来自这里的文档https://facebook.github.io/react/docs/jsx-spread.html
The specification order is important. Later attributes override previous ones.
规范顺序很重要。后来的属性覆盖以前的属性
So if you put your onChange after the spread, it will always take precedence. You can then call the onChange function passed in from your own handler.
因此,如果您在传播之后放置onChange,它将始终优先。然后,您可以调用从您自己的处理程序传入的onChange函数。
var MyInput = React.createClass({
render: function () {
return (
<div>
<input type="text" {...this.props} onChange={this.changeHandler} />
</div>
);
},
changeHandler: function(event){
console.log('Trigger me first');
if (typeof this.props.onChange === 'function') {
this.props.onChange(event);
}
}
});
#1
From the docs here https://facebook.github.io/react/docs/jsx-spread.html
来自这里的文档https://facebook.github.io/react/docs/jsx-spread.html
The specification order is important. Later attributes override previous ones.
规范顺序很重要。后来的属性覆盖以前的属性
So if you put your onChange after the spread, it will always take precedence. You can then call the onChange function passed in from your own handler.
因此,如果您在传播之后放置onChange,它将始终优先。然后,您可以调用从您自己的处理程序传入的onChange函数。
var MyInput = React.createClass({
render: function () {
return (
<div>
<input type="text" {...this.props} onChange={this.changeHandler} />
</div>
);
},
changeHandler: function(event){
console.log('Trigger me first');
if (typeof this.props.onChange === 'function') {
this.props.onChange(event);
}
}
});