React prop-types库使用对组件接收到的props进行类型必要性等限制

父组件:

import React, { Component } from "react"

import Header from "./components/Header"
import Footer from "./components/Footer"
import List from "./components/List"

export default class App extends Component {

  state = { todos: [
    { id: '001', msg: 'Sleep', done: true },
    { id: '002', msg: 'Eat', done: false },
    { id: '003', msg: 'Code', done: false }
  ] }

  addTodo = (todoObj) => {
    const {todos} = this.state
    const newTodos = [todoObj, ...todos]
    this.setState({todos: newTodos})
  }

  changeTodo = (id) => {
    const {todos} = this.state
    const newTodos = todos.map(todo => {
      if (todo.id === id) {
        return {...todo, done: !todo.done}
      } else {
        return {...todo}
      }
    })

    this.setState({todos: newTodos})
  }

  render(){
    const {todos} = this.state
    return(
      <div className="todo-container">
        <Header addTodo={this.addTodo} />
        <List todos={todos} changeTodo={this.changeTodo} />
        <Footer />
      </div>
    )
  }
}

React prop-types库使用对组件接收到的props进行类型必要性等限制_第1张图片

父组件里面给子组件Header传递一个addTodo做为props,这个addTodo是一个函数:

React prop-types库使用对组件接收到的props进行类型必要性等限制_第2张图片

子组件Header:

import React, { Component } from 'react'
import PropTypes from 'prop-types'
import {nanoid} from'nanoid'
import './index.css'

export default class Header extends Component {

  // 对接收的props进行类型和必要性的限制
  static propTypes = {
    addTodo: PropTypes.func.isRequired
  }

  handleKeyUp = (event) => {
    const {keyCode, target} = event
    if (keyCode !== 13) return
    if (target.value.trim() === '') {
      alert('input is empty!')
      target.value = ''
      return
    }
    console.log(target.value, event.keyCode)
    const todoIbj = {id: nanoid(), msg: target.value, done: false}
    this.props.addTodo(todoIbj)
    target.value = ''
  }

  render() {
    return (
      <div className="todo-header">
        <input onKeyUp={this.handleKeyUp} type="text" placeholder="input task name, press enter to confirm" />
      </div>
    )
  }
}

子组件Header如果想要限制props类型和必要性,可以这样:

1.安装prop-types库npm i prop-types

React prop-types库使用对组件接收到的props进行类型必要性等限制_第3张图片

2. 在子组件中引用import PropTypes from 'prop-types', 注意,import后面的是PropTypes,P和T都是大写的

React prop-types库使用对组件接收到的props进行类型必要性等限制_第4张图片

3. 对接收的props进行类型和必要性的限制,注意static关键字和它后面的propTypes,这里的第一个p是小写的

React prop-types库使用对组件接收到的props进行类型必要性等限制_第5张图片

你可能感兴趣的:(react,react.js)