本文將一步步介紹如何使用React或anu創建 一個彈出層。
React時代,代碼都是要經過編譯的,我們很多時間都耗在babel與webpack上。因此本文也介紹如何玩webpack與babel。
我們創建一個ui目錄,里面添加一個package.json。內容如下,里面已經是盡量減少babel插件的使用了。
{ "name": "ui", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "RubyLouvre", "license": "ISC", "devDependencies": { "babel-core": "^6.24.1", "babel-loader": "^6.4.1", "babel-preset-es2015": "^6.24.1", "babel-preset-react": "^6.16.0", "webpack": "^2.2.1" }, "dependencies": { "prop-types": "^15.5.10", "anujs": "^1.0.0" } }
如果你不想用anu,可以改成react與react-dom。
"dependencies": { "prop-types": "^15.5.10" "react": "^15.5.4", "react-dom": "^15.5.4" }
anu本身沒有propTypes,而react最近的版本也把propTypes拆了出來,因此我們需要獨立安裝prop-types這個包。
webpack我們緊隨時髦,使用2.0, 而babel則是一大堆東西。
然后我們在控制台npm install
敲一下,會給我們安裝上幾屏的依賴,下面只是展示了一部分。可見前端的發展多么可怕,以前只是幾個JS文件就覺得非常臃腫了,現在幾百個習以為常。盡管它們大部分是預處理JS的。這也為React帶來巨大的門檻,門檻越高,工資越高。
然后 ui目錄下建立一個src目錄,里面建toast.js。
//第一部分,引入依賴與定義模塊內的全局變量 import React,{Component} from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; let singleton = null; const container = document.createElement('div'), defaultProps = { show: false }, propTypes = { /** * @property show * @description 是否顯示,默認false * @type Boolean * @default false * @skip */ show: PropTypes.bool }; document.body.appendChild(container); //第二部分,定義組件 class ToastReact extends Component { constructor(props) { super(props); this.state = { show: this.props.show, content: '', autoHideTime: 2000 }; this._timer = null; singleton = this; } shouldComponentUpdate(nextProps, nextState) { this.setState({ show: nextState.show }); if (!!this._timer) { clearTimeout(this._timer); this._timer = null; } this._timer = setTimeout(() => this.setState({ show: false }), nextState.autoHideTime); return true; } componentWillUnmount() { clearTimeout(this._timer); document.body.removeChild(container); } render() { const { show, content } = this.state; return ( <div className=