zoukankan      html  css  js  c++  java
  • react--context,高阶组件,hook

    1,Context:不需要在任何组件间添加props方法,可以任意之间的组件树进行
    const Context = React.createContext();
    const Provider = Context.Provider; //提供者
    const Consumer = Context.Consumer; //消费者
    function App() {
    return (
    <div className="App">
    {/* <HomePag {...store} /> */}
    <Provider value={store}>
    <Consumer>
    {ctx=>
    <>
    <div>{ctx.user.name}</div>
    <HomePag {...ctx} />
    </>
    }
    </Consumer>
    </Provider>
    </div>
    );
    }
    2,高阶组件
    一个函数传入一个组件,返回另一个组件
    子组件
    function Child(props) {
    return <div>Child-{props.name}</div>;
    }
    高阶组件
    //这里的Cmp是function或者class组件
    const foo = Cmp => props => {
    // console.log("foo", Cmp);
    return (
    <div className="border">
    <Cmp {...props} />
    </div>
    );
    };
    调用方式
    // const Foo = foo(foo(Child)); // 链式调用
    export default class HocPage extends Component {
    render() {
    return (
    <div>
    <h3>HocPage</h3>
    {/* <Child name="msg" /> */}
    {fooHost(<div>omg</div>)}
    {/* <Foo name="msg" /> */}
    {/* {foo(Child)({ name: "msg" })} */}
    </div>
    );
    }
    }
    如果传入是一个标签,处理的方式有所不同
    //处理原生标签
    const fooHost = cmp => {
    console.log("fooHost", cmp);
    // return cmp;//返回原先的标签
    // return React.cloneElement(cmp, { className: "border" });
    // return React.createElement(cmp.type, { ...cmp.props, className: "border" });
    return <cmp.type {...cmp.props} />;
    // <div className="border">{/* <Cmp /> */}</div>;
    };
    如果采用的是链式调用,child是类,如果是链式调用可以使用装饰器@foo
    // @foo
    // @foo
    // class Child extends Component {
    // render() {
    // return <div>Child-{this.props.name}</div>;
    // }
    // }
    // const Foo = foo(foo(Child)); // 链式调用
    React.cloneElement:浅复制
    React.createElement:赋值
    插槽
    This.props.children
    react的hook
    Hook 是 React 16.8 的新增特性。它可以让你在不编写 class 的情况下使用 state 以及其他的 React 特性。
    1、const [count, setCount] = useState(0);// 状态、函数
    2、Effect Hook 可以让你在函数组件中执行副作用操作
      useEffect(() => {
        // Update the document title using the browser API
        document.title = `You clicked ${count} times`;
      });
    3,useContext
    4,useReducer 可以让你通过 reducer 来管理组件本地的复杂 state。
     
  • 相关阅读:
    汇总遇到的问题
    mybatis下载地址
    快速创建数据大绝招
    常见的dos命令
    添加react-native-icons中文傻瓜式教程
    react native配置环境watchman监控安装失败解决办法
    如何使用SwitchyOmega.crx谷歌插件
    Git与Github学习笔记
    HTTP协议详解
    使用npm安装一些包失败了的解决方法(npm国内镜像介绍),安装速度跟cnpm一样哦
  • 原文地址:https://www.cnblogs.com/yayaxuping/p/12180760.html
Copyright © 2011-2022 走看看