react-zeanium-ui-ui
Version:
Zeanium UI Framework for React.js
105 lines (98 loc) • 2.53 kB
JavaScript
var React = require('react');
module.exports = React.createClass({
displayName:'Select',
getDefaultProps: function () {
return {
textKey: 'text',
valueKey: 'value',
placeholder: "Please Choose..."
};
},
getInitialState:function(){
return {
data: [],
value: this.props.value||''
}
},
componentDidMount:function(){
this._dataSource = Store.dataSource(this.props.data, {
autoLoad: this.props.autoLoad||true,
onSuccess: function (data){
//console.log('Select Loading Success: ', data);
this.__onDataLoaded(data.result || data);
}.bind(this)
});
},
componentWillReceiveProps: function (nextProps){
if(this.props.data!==nextProps.data){
this._dataSource.reset(nextProps.data);
}
},
__onDataLoaded: function (data){
this.setState({ data: data });
if(this.props.fireIndex != undefined){
//this.fireClick(this.props.fireIndex);
}
this.props.onLoaded && this.props.onLoaded(data, this);
},
__onSelectClick: function (event) {
event.stopPropagation();
event.preventDefault();
},
refresh: function () {
this._dataSource.refresh();
},
__parseExp: function (item, exp){
if(typeof exp == 'string'){
if(exp.indexOf('{')!=-1){
return Util.format(exp, item);
} else {
return item[exp];
}
} else if(typeof exp == 'function') {
return exp(item);
}
},
__itemRender: function (item, index){
item = item || {};
if(typeof item === 'string'){
item = { value: item, text: item };
}
var _value = this.__parseExp(item, this.props.valueKey),
_text = this.__parseExp(item, this.props.textKey);
return <option key={index} value={_value}>{_text}</option>;
},
__onSelectChange: function (event){
var _target = event.target,
_selectedIndex = (+_target.selectedIndex - 1),
_item = this.state.data[_selectedIndex],
_value = this.__parseExp(_item, this.props.valueKey),
_text = this.__parseExp(_item, this.props.textKey);
this.setState({
value: _value
});
this.props.onChange && this.props.onChange(event, {
selectedIndex: _selectedIndex,
text: _text,
value: _value,
item: _item
}, this);
},
render:function(){
return (
<select
className="input"
style={this.props.style}
name={this.props.name}
disabled={this.props.disabled}
value={this.state.value}
onChange={this.__onSelectChange}
onClick={this.__onSelectClick}>
<option value="" disabled>{this.props.placeholder}</option>
{
this.state.data.map(this.__itemRender)
}
</select>
);
}
});