学了两天的 React, 做个小 demo 加强认识.
目标: 点击点赞按钮, 冒出一个向上浮动且渐隐的大拇指.
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
| <!DOCTYPE html> <html> <head> <style> #like-button{ top: 100px; position: fixed } .thumb{ position: fixed; } </style> <meta charset="UTF-8" /> <title>Hello React!</title> <script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script> <script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script> <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script> <script src="https://cdn.bootcss.com/prop-types/15.6.1/prop-types.js"></script> </head> <body> <div id="example"></div> <script type="text/babel"> class Thumbup extends React.Component{ constructor(props){ super(props); console.log(this.props.thumb) this.state = {opacity: 1.0, marTop: 100, show: true}; } componentDidMount(){ this.timer = setInterval(function(){ var opacity = this.state.opacity; var marTop = this.state.marTop; opacity -= .005; marTop -= 0.5; if(opacity < 0.01){ clearInterval(this.timer) this.setState({ show: false }); this.props.removeThumb(this.props.thumb) } this.setState({ opacity: opacity, marTop: marTop }) }.bind(this), 10) } componentWillUnmount(){ console.log('unmounting...') } render(){ return this.state.show? <div style={{opacity: this.state.opacity,top: this.state.marTop}} className='thumb'> <img src="https://img.icons8.com/emoji/344/thumbs-up.png" alt="Smiley face" height="20" width="20"/> </div> : null } }
class Button extends React.Component { constructor(props) { super(props); this.state = {comp: null, thumbs: []} this.handleChange = this.handleChange.bind(this); } handleChange() { this.setState({ thumbs: this.state.thumbs.concat([Date.now()]) }) }
removeThumb(val){ let thumbs = this.state.thumbs; this.setState({ thumbs: thumbs.splice(thumbs.indexOf(val), 1) }) }
render() { const thumbs = this.state.thumbs return ( <div> {this.state.thumbs.map(thumb => { return <Thumbup key={thumb} thumb={thumb} removeThumb={this.removeThumb.bind(this)}/> })} <button id='like-button' onClick={this.handleChange}> <span>like</span> <span>👍</span> </button> </div> ); } } ReactDOM.render( <Button />, document.getElementById('example') ); </script> </body> </html>
|