[关闭]
@gongzhen 2019-05-22T10:43:30.000000Z 字数 1020 阅读 1568

组件模板

react


  1. import React, { PropTypes } from 'react';
  2. import deepEqual from 'deep-equal';
  3. import './style.less';
  4. export default class MyComponent extends React.Component {
  5. static propTypes = {
  6. className : PropTypes.string,
  7. value : PropTypes.number
  8. };
  9. static defaultProps = {
  10. className : '',
  11. defaultValue : 0,
  12. //value : 0, //不能为value设置默认值,否则组件会被认为是受控组件
  13. };
  14. constructor(props) {
  15. super(props);
  16. this.state = {
  17. value: 'value' in props ? props.value : props.defaultValue
  18. };
  19. this.handleChange = this.handleChange.bind(this);
  20. }
  21. componentDidMount() {
  22. }
  23. componentWillReceiveProps(nextProps) {
  24. if ('value' in nextProps && !deepEqual(nextProps.value, this.props.value)) {
  25. this.setState({
  26. value: nextProps.value
  27. });
  28. }
  29. }
  30. render() {
  31. const { value, className } = this.state;
  32. let classes = className ? 'my-component ' + className : 'my-component';
  33. return (
  34. <div className={classes}>
  35. {value}
  36. </div>
  37. )
  38. }
  39. handleChange(value) {
  40. this.triggerChange(value);
  41. }
  42. triggerChange(value) {
  43. const { onChange } = this.props;
  44. if ('value' in this.props) {
  45. typeof onChange === 'function' && onChange(value);
  46. }
  47. else {
  48. this.setState({
  49. value: value
  50. }, ()=>typeof onChange === 'function' && onChange(value));
  51. }
  52. }
  53. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注