onChange回调没有在React组件中触发

除非我出于某种原因使用jQuery,否则我的onChange()函数不会运行。 我必须在componentDidMount()添加onChange侦听器的原因是因为我使用的是MaterializeCSS,它将select标签转换为ul 。 以下代码工作正常:

 onChange(e) { let inspectionTime = e.target.value; this.setState({ inspectionTime }); } componentDidMount() { let $inspectionDropdown = $(ReactDOM.findDOMNode(this.refs.inspection)); $inspectionDropdown.on('change', this.onChange); } 

但是这段代码没有:

 onChange(e) { let inspectionTime = e.target.value; this.setState({ inspectionTime }); } componentDidMount() { let inspectionDropdown = ReactDOM.findDOMNode(this.refs.inspection); inspectionDropdown.addEventListener('change', this.onChange); } 

如果它有帮助,这是整个组件的代码:

 import React from 'react'; import ReactDOM from 'react-dom'; class InspectionMode extends React.Component { constructor(props) { super(props); this.onChange = this.onChange.bind(this); this.defaultValue = 'selected'; this.state = { inspectionTime: 0 }; } onChange(e) { let inspectionTime = e.target.value; this.setState({ inspectionTime }); } componentDidMount() { let inspectionDropdown = ReactDOM.findDOMNode(this.refs.inspection); inspectionDropdown.addEventListener('change', this.onChange); } render() { let classes = 'input-field col s10 offset-s1 l3'; return ( 
None 5 Seconds 10 Seconds 15 Seconds
); } } export default InspectionMode;

问题是该插件正在发出自定义更改事件。 React的事件系统无法识别自定义事件(不确定原因)。

在这种情况下,手动更改侦听器是正确的解决方案。 你改进它的方法是将select元素抽象为’atom’。

 class Select extends React.Component { static propTypes = { value: React.PropTypes.string, options: React.PropTypes.arrayOf( React.PropTypes.shape({ text: React.PropTypes.string.isRequired, value: React.PropTypes.string.isRequired, }) ).isRequired }; constructor() { super(); this.onChange = this.onChange.bind(this); } onChange(e) { this.props.onChange(e.target.value); } componentDidMount() { let select = this.refs.select; select.addEventListener('change', this.onChange, false); } componentWillUnmount(){ let select = this.refs.select; select.removeEventListener('change', this.onChange, false); } render() { let classes = 'input-field col s10 offset-s1 l3'; return ( 
); } }

然后,您可以在InspectionMode或UI中的任何其他位置使用此function。

 class InspectionMode extends React.Component { constructor(props) { super(props); this.onChange = this.onChange.bind(this); this.value = 'selected'; this.state = { inspectionTime: 0 }; } onChange(inspectionTime) { this.setState({ inspectionTime }); } render() { return ( 
); } }