react hook 练手
代码:App.js
import React, { useState, useEffect, createContext, useContext, useRef } from 'react';import { Button } from 'antd-mobile';
const Text = createContext(); // useContext 要和 createContext 一起使用
export default function App() {
const inputRef = useRef(); // 操作DOM
const [ count, setCount ] = useState(0);
const [ name, setName ] = useState('张三');
useEffect(() => {
console.log('---------------componentDidMount-------------', count);
return () => {
console.log('---------------componentWillUnmount-------------');
}
},[count]) // componentDidUpdate
const handleClick = () => {
inputRef.current.focus();
}
return (
<div className="App">
<Button onClick={() => setCount(count + 1)}>+1</Button>
<div>{count}</div>
<Button onClick={() => setCount(count - 1)}>-1</Button>
<div>{name}</div>
<Button onClick={() => setName('张三')}>张三</Button>
<Button onClick={() => setName('李四')}>李四</Button>
<Text.Provider value={{ count, setCount }}>
<Item />
</Text.Provider>
<input type="text" ref={inputRef} />
<br />
<Button onClick={handleClick}>Click</Button>
</div>
);
}
function Item () {
const { count, setCount } = useContext(Text);
return (
<div>
Item_count:{count}
<br />
<Button onClick={() => setCount(count - 1)}>-1</Button>
</div>
);
}
.
以上是 react hook 练手 的全部内容, 来源链接: utcz.com/z/384108.html