[React] Remove React PropTypes by using Flow Annotations (in CRA)

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[React] Remove React PropTypes by using Flow Annotations (in CRA)相关的知识,希望对你有一定的参考价值。

Starting from v15.5 if we wanted to use React‘s PropTypes we had to change our code to use a separate node module, now we can go one step further and get rid of that extra dependency just by using flow type annotations in our create-react-app project!

 

Install:

yarn add flow-bin

 

Scripts:

"flow": "flow"

 

Run:

npm run flow init
npm run flow

 

Add flow annotations:

// @flow

import {createStore} from ‘redux‘;
import reducer from ‘./reducers/todo‘;

export type TodoType = {
    id: number,
    name: string,
    isComplete: boolean
};

export type StateType = {
    todos: Array<TodoType>,
    currentTodo: string
};

const initState: StateType = {
    todos: [
        {id: 1, name: ‘Render static UI‘, isComplete: true},
        {id: 2, name: ‘Create initial state‘, isComplete: false},
        {id: 3, name: ‘Render based on state‘, isComplete: true}
    ],
    currentTodo: ‘Temp‘
};

const store = createStore(reducer, initState);

export default store;

 

Import a flow type:

// @flow
import React from ‘react‘
import {connect} from ‘react-redux‘;
import type {TodoType} from ‘../store‘;


const TodoItem = ({id, name, isComplete}: TodoType) => (
    <li>
        <input type="checkbox" defaultChecked={isComplete} />
        {name}
    </li>
)

const TodoList =  (props: {todos: Array<TodoType>}) => (
    <div className="Todo-List">
        <ul>
            {props.todos.map(todo => <TodoItem key={todo.id} {...todo} />)}
        </ul>
    </div>
);

export default connect(
    (state) => ({todos: state.todos})
)(TodoList);

 

以上是关于[React] Remove React PropTypes by using Flow Annotations (in CRA)的主要内容,如果未能解决你的问题,请参考以下文章

如何测试 React 组件的 prop 更新

react+antd Failed prop type: Invalid prop `value` supplied to `Select`.

为啥系统在“prop-types”中寻找“react-is”?

React 传递函数作为 prop

断言一个 Prop 包含一个 React 组件

为啥 React 组件库更喜欢基于 prop 的样式