|
| 1 | +import React, { useState, useEffect } from 'react'; |
| 2 | +import styled from 'styled-components'; |
| 3 | +import { CSSTransition } from 'react-transition-group' |
| 4 | + |
| 5 | + |
| 6 | +const StyledDiv = styled.div` |
| 7 | + width: 500px; |
| 8 | + height: 300px; |
| 9 | + text-align: center; |
| 10 | + .line { |
| 11 | + height: 50px; |
| 12 | + line-height: 50px; |
| 13 | + } |
| 14 | + .line-height button{ |
| 15 | + background-color: black; |
| 16 | + color: #fff; |
| 17 | + } |
| 18 | + .fade-enter{ |
| 19 | + opacity: 0; |
| 20 | +} |
| 21 | +.fade-enter-active{ |
| 22 | + opacity: 1; |
| 23 | + transition: opacity 2000ms; |
| 24 | +
|
| 25 | +} |
| 26 | +.fade-enter-done{ |
| 27 | + opacity: 1; |
| 28 | +} |
| 29 | +.fade-exit{ |
| 30 | + opacity: 1; |
| 31 | +} |
| 32 | +.fade-exit-active{ |
| 33 | + opacity: 0; |
| 34 | + transition: opacity 2000ms; |
| 35 | +
|
| 36 | +} |
| 37 | +.fade-exit-done{ |
| 38 | + opacity: 0; |
| 39 | +} |
| 40 | +`; |
| 41 | +function Page() { |
| 42 | + const [color, setColor] = useState('blue'); |
| 43 | + const [show, setShow] = useState(true); |
| 44 | + function changeTab(index) { |
| 45 | + if (color === index) { |
| 46 | + return; |
| 47 | + } |
| 48 | + console.log('改变颜色', index); |
| 49 | + setColor(index); |
| 50 | + }; |
| 51 | + return ( |
| 52 | + <StyledDiv> |
| 53 | + <h4>若父组件选择了blue按钮,子组件则不重复render</h4> |
| 54 | + <div className={`line ${color === 'blue' && 'line-height'}`}> |
| 55 | + <button onClick={() => changeTab('blue')}>blue</button> |
| 56 | + </div> |
| 57 | + <div className={`line ${color === 'red' && 'line-height'}`}> |
| 58 | + <button onClick={() => changeTab('red')}>red</button> |
| 59 | + </div> |
| 60 | + <div className={`line ${color === 'black' && 'line-height'}`}> |
| 61 | + <button onClick={() => changeTab('black')}>black</button> |
| 62 | + </div> |
| 63 | + <div className="line"> |
| 64 | + <button onClick={() => setShow(!show)}>toggleShow</button> |
| 65 | + </div> |
| 66 | + <CSSTransition |
| 67 | + in={show} //用于判断是否出现的状态 |
| 68 | + timeout={800} //动画持续时间 |
| 69 | + classNames="fade" //className值,防止重复 |
| 70 | + unmountOnExit |
| 71 | + > |
| 72 | + <Son color={color} /> |
| 73 | + </CSSTransition> |
| 74 | + </StyledDiv> |
| 75 | + ) |
| 76 | +} |
| 77 | + |
| 78 | +class Son extends React.Component { |
| 79 | + constructor(props) { |
| 80 | + super(props); |
| 81 | + this.state = { |
| 82 | + } |
| 83 | + }; |
| 84 | + shouldComponentUpdate(nextProps,nextState){ |
| 85 | + if(nextProps.color !== 'blue'){ |
| 86 | + return true |
| 87 | + }else{ |
| 88 | + return false |
| 89 | + } |
| 90 | + } |
| 91 | + render() { |
| 92 | + console.log('来咯来咯'); |
| 93 | + return ( |
| 94 | + <div style={{ color: this.props.color }}>1111</div> |
| 95 | + ) |
| 96 | + } |
| 97 | +} |
| 98 | +export default Page; |
0 commit comments