我正在使用Chrome版本37并使用React 16. onClick
功能在该版本中无效。实际上,浏览器不显示事件侦听器,并且单击时没有任何操作。代码显示没有错误。
具体而言,以下内容不起作用:
<SelectOption onClick={() => this.handleOptionClick(item) }>
<div>{item.image ? that.renderOptionImage(item.image) : null}{item.text}</div>
<div>{item.optionalText ? item.optionalText : null}</div>
</SelectOption>
完整的代码是:
import {Component} from 'react';
import PropTypes from 'prop-types';
import {Select, SelectOption, OptionImage} from './styles';
class SelectBox extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.showList = false;
this.activeItem = null;
}
renderOptionImage(image) {
return (
<OptionImage src={image} ></OptionImage>
);
}
updateActiveItem(item) {
this.renderSelectedItem(item);
// display active item in search box
// var currentElement = ReactDOM.findDOMNode(this);
// {this.renderSelectedItem()}
}
renderSelectedItem(item) {
console.log("I am here in ter tiem");
if (item) {
return (<div>
<div>renderOptionImage(item.image) {item.text}</div>
<div>{item.optionalText}</div>
</div>)
}
else {
return (<div>Select your Item</div>)
}
}
onClick() {
this.setState({
showList: !showList
});
this.renderOptions();
}
renderOptions () {
console.log(this.showList);
const that = this;
var data = [
{'text': 'Item 1',
'image': 'http://placehold.it/120x120&text=image1',
'optionalText': 'item 1'
},
{'text': 'Item2',
'image': 'https://www.gstatic.com/webp/gallery/4.sm.jpg',
'optionalText': 'item 1'
},
{'text': 'Item2',
'optionalText': 'item 1'
},
{'text': 'Item2',
'image': '',
}
];
if (this.showList) {
return data.map((item, i) => {
return (
<SelectOption onClick={() => this.handleOptionClick(item) }>
<div>{item.image ? that.renderOptionImage(item.image) : null}{item.text}</div>
<div>{item.optionalText ? item.optionalText : null}</div>
</SelectOption>);
});
}
}
handleOptionClick = (item) => {
console.log('I am handling this');
// update the select main content
this.updateActiveItem(item)
}
render() {
const props = this.props;
const {showList} = this.state;
return (
<div>
<Select id={this.props.id} name={this.props.name} >{this.renderSelectedItem()}</Select>
{this.renderOptions()}
</div>
);
}
}
SelectBox.propTypes = {
name: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
};
SelectBox.defaultProps = {
name: 'Select yout item from the following',
id: 'select-one'
};
export default SelectBox;