码迷,mamicode.com
首页 > 其他好文 > 详细

react--context,高阶组件,hook

时间:2020-01-11 20:22:28      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:fir   date   VID   source   ocs   另一个   bcf   store   api   

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。
 

react--context,高阶组件,hook

标签:fir   date   VID   source   ocs   另一个   bcf   store   api   

原文地址:https://www.cnblogs.com/yayaxuping/p/12180760.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!