react 实践

作者: 别过经年 | 来源:发表于2017-08-09 18:23 被阅读43次

    1. es6扩展运算符将组建嵌套的dom渲染到组件内部

    查看react-component/dialog的时候发现了直接使用...props将组件的嵌套标签渲染到组件内部的情况,做了如下实验。

    PaperItem.tsx

    import * as React from "react";
    
    export interface Props {
      name: string;
      enthusiasmLevel?: number;
      onIncrement?: () => void;
      onDecrement?: () => void;
    }
    
    export default function PaperItem(props: Props) {
      return <div className="paper-item" {...props} />;//使用扩展运算符
    }
    

    PaperList.tsx

    import * as React from "react";
    import PaperItem from "../components/PaperItem";
    
    export default class PaperList extends React.Component {
      data = {
        name: 99
      };
      render() {
        return (
          <div>
            {[1, 2, 3, 4].map(x =>
              <PaperItem key={x} name={String(x)}>
                <h1>ii</h1>//将这两行插入到PaperItem里面
                <h2>oo</h2>
              </PaperItem>
            )}
          </div>
        );
      }
    }
    

    渲染结果:


    name props会渲染到展开他的标签上,而children就作为该标签的子节点渲染出来了,通常是使用tihs.props.children拿到组件里面嵌套的标签,然后遍历出来,这么写的确是一条捷径。
    vue有slot可以轻松做到嵌套的dom,渲染到组件内部,命名slot的占位作用可以准确的定位要插入的位置和数量,react这边有待发现。
    昨晚查阅了react官方文档,在组合 vs 继承章节,详细说明了props.children的使用和类似vue slot的使用,类似slot的占位和多个外部dom或者组件片段插入组件,react是通过props实现的,props可以传递基础数据类型,函数,原生的dom,或者组件。这样就很方便了。
    2. 组件类型
    • 1.类组件合函数组件(无状态函数组件)
      在官网组件 & Props提到了累组件和函数组件,函数组件没有state没有生命周期函数,所以每次更新都是由外面传入的props的改变引起的,而且渲染速度比类组件要快。一般函数组件作为展示组件使用,展示数据和效果,状态的改变交给外部的类组件,对于redux来说就是容器组件,在react定义d.ts接口的时候定义了如下的接口:
        type SFC<P = {}> = StatelessComponent<P>;
        interface StatelessComponent<P = {}> {
            (props: P & { children?: ReactNode }, context?: any): ReactElement<any> | null;
            propTypes?: ValidationMap<P>;
            contextTypes?: ValidationMap<any>;
            defaultProps?: Partial<P>;
            displayName?: string;
        }
    
        interface ComponentClass<P = {}> {
            new (props?: P, context?: any): Component<P, ComponentState>;
            propTypes?: ValidationMap<P>;
            contextTypes?: ValidationMap<any>;
            childContextTypes?: ValidationMap<any>;
            defaultProps?: Partial<P>;
            displayName?: string;
        }
    
        interface ClassicComponentClass<P = {}> extends ComponentClass<P> {
            new (props?: P, context?: any): ClassicComponent<P, ComponentState>;
            getDefaultProps?(): P;
        }
    

    所以在定义一个函数类的时候可以去这么定义:

    import * as React from 'react'
    export interface LockPropType {
      src: any
      onClick?: (e?: any) => void
    }
    const Lock: React.StatelessComponent<LockPropType> = ({ src, ...restProps }) => {
      return (
        <div>
        </div>
      )
    }
    export default Lock
    

    谈一谈创建React Component的几种方式

    3. 等待state更新完后,利用更新后的state值去做其他操作

    项目里每个有的页面是公用的,不同的路由有公用一个组件。这个时候路由的props match改变了所以走了componentWillReceiveProps钩子函数,这时候需要初始化页面的state,并利用初始化后的参数做ajax请求。那么就可以使用setState(updater, [callback])

    this.setState({name:'geek'},()=>{
      request('url',{name:this.state.name}).then()
    })
    

    react-component有详细说明

    2. Children.only(this.props.children)

    在读react-redux/src/components/Provider.js源码的时候遇到了这么一句话

        class Provider extends Component {
            render() {
              return Children.only(this.props.children)
            }
        }
    

    然后结合实际的项目看

    import React from 'react'
    import { render } from 'react-dom'
    import { createStore } from 'redux'
    import { Provider } from 'react-redux'
    import App from './components/App'
    import reducer from './reducers'
    
    const store = createStore(reducer)
    
    render(
      <Provider store={store}>
        <App />//那就是Provider组件只能包含一个根子组件,也就是一个对象,而不是数组
      </Provider>,
      document.getElementById('root')
    )
    

    React.Children是react顶层的api其他文档可参考React 顶层 API

    3. 使用vscode调试create-react-app

    VSCode debugging with Create-React-App

    Debugging in the Editor

    4. react拖拽生成组件代码

    拖拽生成组件,大家react怎么实现?

    5. redux-devtools 配置

    • 不安装Chrome redux devtools
      使用 Redux-devTools简单的使用 这种方式会在页面生成redux devtools
    • 安装Chrome redux devtools 那么默认就使用Chrome redux devtools
    store = createStore(
            combineReducers(reducers),
            compose(applyMiddleware(thunk),window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()) //插件调试,未安装会报错
        );
    

    使用Redux DevTools浏览器插件调试redux

    相关文章

      网友评论

        本文标题:react 实践

        本文链接:https://www.haomeiwen.com/subject/fvpqrxtx.html