React初体验
React组件以及如何使用外部数据props和内部数据state
React类组件以及函数组件实现多个state以及分级state
reverent-water-bvow3 - CodeSandbox
react 的class组件
class App extends React.PureComponent { //用于代替钩子shouldComponentUpdate
constructor(props) { //初始化props
super(props);
this.state = {
n: 1,
array: [1,2,3]
}
}
onClick = () => {
this.setState((state) => ({n: state.n + 1})) //建议这样写事件绑定函数或者是setState
}
//{n:1} 和 {n:1}
// shouldComponentUpdate(newProps,newState) { //钩子shouldComponentUpdate的用法,可以手动确定是否要进行组件的更新(主要是针对于render里的数据)
// if (newState.n===this.state.n){
// return false
// }else{
// return true
// }
// }
componentDidMount() { //钩子componentDidMount的用法,在元素插入页面后执行,其中的代码一般依赖DOM
const div = document.getElementById('xx') //或者使用ref来获取
const {width} = div.getBoundingClientRect() //析构语法
this.setState({width})//等价于this.setState({width:width})
}
render() {
// let message //render中还可以写if else语句,可以写?:表达式。但别写for循环,因为第一次return循环会结束
// if (this.state.n % 2 === 0) {
// message = <div>偶数</div>
// } else {
// message = <span>奇数</span>
// }
return (
<>
{this.state.n % 2 === 0 ?
<div>偶数</div> :
<span>奇数</span>}
<button onClick={this.onClick}>+1</button>
</>
)
//return this.state.array.map(n=><div key={n}>{n}</div>) //代替for循环
}
// const Component1 = (props) => {
// const array = []
// for (let i = 0; i < props.numbers.length; i++) {
// array.push(<div> {i}
// {props.numbers[i]}</div>)
// }
// return <div>{array}</div>
// }
}
react 函数组件
模拟class组件中的钩子
const App = props => {
const [n, setN] = useState(0)
const onClick = () => {
setN(n + 1)
}
useEffect(()=>{ //使用useEffect来模拟
console.log('use effect')
},[]) //第二个参数为[]时,表示模拟componentDidMount;想要模拟哪个变量的变化,就在第二个参数写哪个变量 模拟componentDidUpdate,但与class组件比,这种方法在第一次 渲染时也会调用,如何不让第一次渲染时调用? 见下面自定义hooks
return (
<>
<div>
{n}
</div>
<button onClick={onClick}>+1</button>
</>
)
}
/////
const App = props => {
const [n, setN] = useState(false)
const hide = () => {
setN(false)
}
const appear = () => {
setN(true)
}
return (
<>
{n ? <button onClick={hide}>隐藏</button> : <button onClick={appear}>出现</button>}
{n ? <Child></Child> : null}
</>
)
}
const Child = props => {
useEffect(() => {
console.log("渲染或者变化了")
return () => { //在useEffect中再次返回的函数会在组件将要销毁时调用即模拟 componentWillUnmount
console.log("我挂了")
}
})
return (
<div>child</div>
)
}