react PropTypes怎么校验传递的值

发布时间:2020-07-29 14:58:09 作者:小猪
来源:亿速云 阅读:128

这篇文章主要讲解了react PropTypes怎么校验传递的值,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

校验传递的值:

import React, { Component, Fragment } from 'react';
import List from './List.js';
 
class Test extends Component {
  constructor(props) {
    super(props);
    this.state={
      inputValue:'aaa',
      list:['睡觉','打游戏'],
    }
    // this.add=this.add.bind(this);
  }
 
  addList() {
    this.setState({
      list:[...this.state.list,this.state.inputValue],
      inputValue:''
    })
  }
 
  change(e) {
    this.setState({
      inputValue:e.target.value
    })
  }
 
  delete(i) {
    // console.log(i);
    const list = this.state.list;
    list.splice(i,1);
    this.setState({
      list:list
    })
  }
 
  render() { 
    return (
      <Fragment>
      <div>
        <input value={this.state.inputValue} onChange={this.change.bind(this)}/>
        <button onClick={this.addList.bind(this)}>添加</button>
      </div>
      <ul>
        {
          this.state.list.map((v,i)=>{
            return(
                <List key={i} content={v} index={i} delete={this.delete.bind(this)} />
            );
          })
        }
      </ul>
      </Fragment>
    );
  }
}
export default Test;
import React, { Component } from 'react';
import PropTypes from 'prop-types';
 
class List extends Component {
  constructor(props) {
    super(props);
    this.delete = this.delete.bind(this);
  }
 
  render() { 
    return (
    <li
      onClick={this.delete}
    >{this.props.name}{this.props.content}</li>
    );
  }
 
  delete=() => {
    this.props.delete(this.props.index);
  }
}
 
//传值校验
 
List.propTypes={
  name:PropTypes.string.isRequired,
  content:PropTypes.string,
  index:PropTypes.number,
  delete:PropTypes.func
}
 
//设置默认值:
 
List.defaultProps={
  name:'张三'
}
 
export default List;

看完上述内容,是不是对react PropTypes怎么校验传递的值有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. React基本概念(二)
  2. React组件怎么用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

react proptypes 的值

上一篇:oracle的启动与关闭原理-参数文件管理

下一篇:如何使用C++顺序表

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》