美文网首页
React相关

React相关

作者: 还是踢球吧777 | 来源:发表于2018-03-03 09:11 被阅读0次

propType检测数据类型

import PropTypes from 'prop-types';

class Counter extends Component {

  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <button style={buttonStyle} onClick={this.onClickIncrementButton}>+</button>
        <button style={buttonStyle} onClick={this.onClickDecrementButton}>-</button>
        <span>{caption} count: {this.state.count}</span>
      </div>
    );
  }
}

//检查传入的prop是否为想要的数据类型,isrequired表示该数据类型是必须的,不能为空
Counter.propTypes = {
  caption: PropTypes.string.isRequired,
  initValue: PropTypes.number
};

defaultProps设置默认prop

import PropTypes from 'prop-types';

class Counter extends Component {

  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <button style={buttonStyle} onClick={this.onClickIncrementButton}>+</button>
        <button style={buttonStyle} onClick={this.onClickDecrementButton}>-</button>
        <span>{caption} count: {this.state.count}</span>
      </div>
    );
  }
}

//设置传入的prop默认值
Counter.defaultProps= {
  initValue: 0
};

相关文章

网友评论

      本文标题:React相关

      本文链接:https://www.haomeiwen.com/subject/kcctfftx.html