@gongzhen
2019-05-22T18:43:30.000000Z
字数 1020
阅读 1699
react
import React, { PropTypes } from 'react';
import deepEqual from 'deep-equal';
import './style.less';
export default class MyComponent extends React.Component {
static propTypes = {
className : PropTypes.string,
value : PropTypes.number
};
static defaultProps = {
className : '',
defaultValue : 0,
//value : 0, //不能为value设置默认值,否则组件会被认为是受控组件
};
constructor(props) {
super(props);
this.state = {
value: 'value' in props ? props.value : props.defaultValue
};
this.handleChange = this.handleChange.bind(this);
}
componentDidMount() {
}
componentWillReceiveProps(nextProps) {
if ('value' in nextProps && !deepEqual(nextProps.value, this.props.value)) {
this.setState({
value: nextProps.value
});
}
}
render() {
const { value, className } = this.state;
let classes = className ? 'my-component ' + className : 'my-component';
return (
<div className={classes}>
{value}
</div>
)
}
handleChange(value) {
this.triggerChange(value);
}
triggerChange(value) {
const { onChange } = this.props;
if ('value' in this.props) {
typeof onChange === 'function' && onChange(value);
}
else {
this.setState({
value: value
}, ()=>typeof onChange === 'function' && onChange(value));
}
}
}