本文将一步步介绍如何使用React或创建 一个弹出层。
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 (