react PropTypes校驗傳遞的值操作示例
阿新 • • 發佈:2020-04-29
本文例項講述了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程式設計有所幫助。