1.安装node及npm环境
2.在cmd命令窗口输入npm install -g create-react-app,或者使用淘宝定制的cnpm,
npm install -g cnpm --registry=https://registry.npm.taobao.org
npm config set registry https://registry.npm.taobao.org
然后cnpm install -g create-react-app
3. 创建项目 create-react-app my-app,进入项目目录cd my-app/,启动项目npm start
4.react模块化
//HelloWorld.js模块
import React from 'react';
import { NavLink } from 'react-router-dom'
import './HelloWorld.css';
class HelloWorld extends React.Component{
constructor(props) {
// 使用super()将props传递给基础构造函数
super(props);
this.state = {opacity: 1.0};
}
componentDidMount() {
/*this.timer = setInterval(function () {
var opacity = this.state.opacity;
opacity -= .05;
if (opacity < 0.1) {
opacity = 1.0;
}
this.setState({
opacity: opacity
});
}.bind(this), 100);*/
}
doSome(e){
e.preventDefault();
alert(3435);
}
test(){
alert("mousemove...");
}
render () {
return (
<div>
<div style={{opacity: this.state.opacity}} className="hello-header" onClick={this.doSome} onTouchMove={this.test}>
Hello {this.props.name}
</div>
<NavLink exact={false} to="/user">User</NavLink>
</div>
);
}
}
export default HelloWorld;
//Home.js
import React from 'react';
import HelloWorld from '../helloworld/HelloWorld';
class Home extends React.Component{
constructor(props) {
// 使用super()将props传递给基础构造函数
super(props);
this.state={};
}
render(){
return (
<HelloWorld name="React"></HelloWorld>
);
}
}
export default Home;
5.路由 react-router-dom
5.1 安装 cnpm install react-router-dom --save
5.2 在app入口文件中引入
import React from 'react';
import { HashRouter as Router,Route} from 'react-router-dom';
import Home from './component/home/Home'
import User from './component/user/User'
import './App.css';
class App extends React.Component {
render() {
return (
<Router>
<div>
<Route path='/' exact={true} component={Home}></Route>
<Route path='/user' component={User}></Route>
</div>
</Router>
);
}
}
export default App;
5.3 在组件中使用NavLink或Link标签
<NavLink exact={false} to="/user">User</NavLink>
6.状态管理Redux,非父子组件传值
6.1安装 cnpm install react-redux --save cnpm install redux --save
6.2 action view中派发的事件
//index .js
export const addTodo = {
type: 'ADD_TODO'
}
6.3 reducer
//todos.js
const todos = (state = {number: 0}, action) => {
let number = state.number
switch (action.type) {
case 'ADD_TODO':
return {number: number+1}
default:
return state
}
}
export default todos
6.4在组件中使用全局state
//User.js
import React from 'react';
import { connect } from 'react-redux';
import {addTodo} from '../../actions';
//状态值管理
const mapStateToProps = (state) => {
return {
count: state.number
}
};
//事件派发
const mapDispatchToProps = (dispatch, ownProps) => {
return {
btnTest: ()=>dispatch(addTodo)
}
};
class User extends React.Component{
constructor(props) {
super(props);
this.state={};
}
render(){
const { count, btnTest} = this.props
return (
<div>
User {count}
<button onClick={btnTest}>点我</button>
</div>
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(User);
Redux原理
网友评论