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() {
// }
// }
// 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` ;
} ) ;
// Update the document title using the browser API
document . title = `You clicked ${ count } times` ;
} ) ;
3,
useContext