让React组件像DOM组件那样触发更改事件
Have React component trigger a change event the way DOM components would
我有一个React Component,它封装了<input type='text' />
,但仅在值更改为有效值时调用onChange
。(它自己的状态允许它更改输入的文本值,但当它调用onChange
时,它实际上返回了一个输入解析值的对象。)
export default class MyInputClass extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = { textValue: '' };
// ...
}
// ...
handleChange(e) {
// set the state regardless of value so the input's text changes
this.setState({ textValue: e.target.value});
// determine whether the value is valid, and if so, call onChange()
let myObj = MyParsedObject.parse(e.target.value);
if (myObj !== null && this.props.onChange) {
this.props.onChange(myObj);
}
}
render() {
return <input onChange={this.handleChange} value={this.state.textValue} />;
}
}
// ...
MyInputClass.propTypes = {
onChange: React.PropTypes.func
};
现在我有一个属性onChange
,它是一个React.PropTypes.func
,当输入的更改被触发时,我尝试解析输入的值。如果成功,我会检查this.props.onChange
是否不是null
,然后调用onChange(myParsedObject)
。
这是有效的,但感觉不对。onChange
的处理程序应该期望一个Event参数(或React中的SyntheticEvent),而不是一个对象。此外,这种模式只允许onChange
使用一个处理程序,而实际事件可以有多个处理程序。
您应该如何设计React Components来发射真实事件?
如果MyInputClass
被设计成围绕输入的通用包装器,那么用事件而不是解析的输入来调用this.props.onChange
,并让父组件决定如何解析它可能是有意义的。但是,如果MyInputClass
是特定于的类型输入的包装器,则也传递解析的值可能是有道理的。您可以同时做这两件事,并使其成为API的显式部分:
this.props.onChange(e, myObj);
或者使用onChange
作为通用处理程序,onWhateverChange
作为解析版本;例如,对于JsonInput
组件,可以执行
this.props.onChange(e);
this.props.onJsonChange(parsedJson);
相关文章:
- 如何向onClick事件处理程序传递一个接受参数的函数,并且仍然将该函数绑定到组件's”;这个“;上下文
- 单元测试:使用酶模拟父组件中子组件的点击事件
- React/flux - 子组件用户事件 - 是否应通过调度程序路由所有内容
- React:如何侦听子组件事件
- 将事件绑定到其他UI组件's函数,在Kendo MVVM中
- 如何更新angular2中组件之间的事件数据
- 点击tpl链接时,ExtJS 4.2自定义组件触发事件
- 反应:在嵌套组件上冒泡点击事件
- 如何根据其他组件中的事件更新组件URL
- 使用Ember中的组件生命周期事件
- 如何将事件绑定到模式对话框上的组件
- 将事件处理程序推送到父组件
- React,在组件事件上呈现消息的最佳方法
- 如何确定Twitter引导组件事件的来源
- 取消ExtJS组件事件
- Ember:嵌套组件事件冒泡
- 获取飞行组件事件的委托目标
- EmberJS嵌套组件事件
- Angular js文本Angular组件事件上键
- ExtJS“创建”或“初始化”组件事件侦听器