function () {
return class extends Component {
constructor(props) {
super(props);
}
render() {
return < {
...this.props} />
}
}
}
or
import React, {
useState } from 'react';
const BlogAddress = ()=>{
const [type, settype] = useState(0);
return (
<div>
{
type}
</div>
)
}
export default BlogAddress;
useState等价于class写法中的this.state
const [当前状态键名,修改状态函数名] = useState(当前状态初始值)
const [type, settype] = useState(0);
const [aa, setAa] = useState('棒子');
```w
**使用:**
```javascript
<div className="right detail_content"> {
type} </div>
<div className="right detail_content"> {
aa} </div>
<button onClick={
() => settype(type=> type - 1)}>-</button>
React是根据useState出现的顺序来确定对应的state。React Hooks不能出现在条件判断语句中,因为它必须有完全一样的渲染顺序。
引入:
↓
import React, {
useEffect } from "react";
↑
useEffect(() => {
return () => {
};
}, []);
demo:
import React, {
useEffect, useState } from 'react';
const BlogAddress = ()=>{
const [count , SetCount] = useState(0)
useEffect(()=>{
console.log(`${
count}`)
})
return (
<div>
<button onClick={
()=>{
SetCount(count+1)}}>
add
</button>
</div>
)
}
export default BlogAddress;
在return + 第二参数 []
useEffect(() => {
console.log(`${
count}`);
return () => {
console.log(`goodbyeBlog`);
};
}, []);
这时候是会发生在页面注销阶段
如果你想在每次函数执行完后将空数组写上对应的就可以了
useEffect(() => {
console.log(`${
count}`);
return () => {
console.log(`goodbyeBlog`);
};
}, [count]);
写法记录:
useEffect(() => {
return () => {
};
}, []);
如果不是将两个hooks写在了一个组件中则无需暴露——分开写的话需要暴露
引入:
import React, {
useState , createContext } from 'react';
↓
const CountContext = createContext();
↑
return部分:
<CountContext.Provider value={
count}>
<Counter />
</CountContext.Provider>
function Counter(){
const count = useContext(CountContext) //一句话就可以得到count
return (<h2>{
count}</h2>)
}
引入useContext:
↓
import React, {
useState, useEffect, createContext } from "react";
↑
声明useContext:
const [type, settype] = useState(0);
↓
export const rightContent = createContext();
↑
return部分:
<rightContent.Provider value={
type}> //1.rightContent这个是你在使用createContext取的名字 2.在value里面写上你要传递的值
<BlogAddress /> //你的子组件
</rightContent.Provider>
引入:
↓
import React, {
useEffect, useState, useContext } from "react";
↑
↓
import {
rightContent} from '../../view/home/homeUi';//将之前暴露的引入过来
↑
hook部分:
↓
let msg = useContext(rightContent);
↑
return部分:
↓
<div> {
msg} </div>
↑
父组件部分:
const [type, changeType] = useState(1);
useEffect(() => {
console.log(type)
return () => {
};
}, [type]);
↓
<Nav changeType={
changeType}></Nav>
↑
子组件为class部分:
getKey(e) {
↓
this.props.changeType(e.key);
↑
}
↓
<Menu.Item key={
item.key} onClick={
this.getKey}>
↑
<Icon type={
item.type} />
{
item.name}
</Menu.Item>