react PropTypes校验传递的值操作示例
程序员文章站
2024-01-25 23:29:02
本文实例讲述了react proptypes校验传递的值操作。分享给大家供大家参考,具体如下:校验传递的值:import react, { component, fragment } from 're...
本文实例讲述了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程序设计有所帮助。