react基础文档

react

1. jsx语法规则
  • 样式类名要使用 className
  • 内联样式要使用 style={{key:value}} 示例:style={{color:'white',fontSize:'29px'}}
  • list循环 {data.map((item,index) => {return
  • {item.name}
  • })}
2.react中定义组件
  • 函数式组件: function MyComponent(){return

    函数式组件

    }
  • 类组件: class MyComponent extends React.Component {render(){}}
3.组件实例props
  • 对标签属性进行类型、必要性的限制
static propTypes = {
    name:PropTypes.string.isRequired, //限制name必传,且为字符串
    sex:PropTypes.string,//限制sex为字符串
    age:PropTypes.number,//限制age为数值
}
  • 设置默认值、
//指定默认标签属性值
static defaultProps = {
    sex:'男',//sex默认值为男
    age:18 //age默认值为18
}
4.组件实例ref
  • 回调使用 ref={c => this.input1 = c } 使用 const value = this.input1.value
  • createRef方式 ref={this.myRef} 使用 myRef = React.createRef()
5.高阶函数-函数柯里化 存状态的表示受控组件
  • 通过传值方式,获取多个输入框输入得值,多个值存form对象中
<input onChange={this.saveFormData('username')} type="text" name="username" />
<input onChange={this.saveFormData('username')} type="text" name="username" />

state = {
    form: {
        username: '', //用户名
        password: '' //密码
    }
}

//保存表单数据到状态中  key接受的是状态key    event获取值  
saveFormData = (key) => {
	return (event) => {
		let form = this.state.form
		for (let item in this.state.form) {
			if (item === key) {
				form[item] = event.target.value
				this.setState({ form: form })
			}
		}
	}
}

//单个值
saveFormData = (dataType)=>{
    return (event)=>{
   		+this.setState({[dataType]:event.target.value})
    }
}
6.生命周期
  • 组件挂载完毕的钩子 componentDidMount(){}
  • 组件将要卸载的钩子 componentWillUnmount(){}
  • 组件更新完毕的钩子 componentDidUpdate(){}
7.脚手架创建项目
  • create-react-app my-project 注:不允许使用驼峰命名
8.跨域配置代理
1.在src下创建配置文件:src/setupProxy.js
2.setupProxy.js
const proxy = require('http-proxy-middleware')
module.exports = function(app) {
     app.use(
       proxy('/api', {  
         target: 'http://localhost:5000',
         changeOrigin: true, 
         pathRewrite: {'^/api': ''} 
       }),
       proxy('/api2', { 
         target: 'http://localhost:5001',
         changeOrigin: true,
         pathRewrite: {'^/api2': ''}
       })
     )
   }
9.路由组件 (pages)
  • 安装路由: npm i react-router-dom
    
  • 一般路由

    import {Link,Route} from 'react-router-dom'
    
    <Link to="/about">Home</Link>   to:去哪里
    
    <Route path="/about" component={About}/>  path:路由路径  component:引入路由组件
    
    //包裹
    import {BrowserRouter} from 'react-router-dom'
    <BrowserRouter><App/></BrowserRouter>,
    
  • NavLink

    可以通过activeClassName加鼠标点击得样式  .xxx{}
    
    import {NavLink,Route} from 'react-router-dom'
    
    <NavLink activeClassName="xxx" to="/about">Home</NavLink>
    
    <Route path="/home" component={Home}/>
    
  • 封装NavLink

    1. components下新建 MyNavLink文件
    
    2. MyNavLink.jsx
    import {NavLink} from 'react-router-dom'
    <NavLink activeClassName="atguigu" {...this.props}/>
    
    3.使用
    <MyNavLink to="/home">Home</MyNavLink>
    <Route path="/home" component={Home}/>
    
  • Switch

    import {Route,Switch} from 'react-router-dom'
    
    <Switch>
    	<Route path="/home" component={Home}/>
    	<Route path="/home" component={Test}/>
    </Switch>
    
    单一匹配
    
  • 解决样式丢失问题

    1. <link rel="stylesheet" href="/css/bootstrap.css">
    
    2. <link rel="stylesheet" href="%PUBLIC_URL%/css/bootstrap.css">
    
    3. 使用HashRouter
    
  • 路由的严格匹配与模糊匹配

    1.默认使用的是模糊匹配(简单记:【输入的路径】必须包含要【匹配的路径】,且顺序要一致)
    2.开启严格匹配:<Route exact={true} path="/about" component={About}/>
    3.严格匹配不要随便开启,需要再开,有些时候开启会导致无法继续匹配二级路由
    
  • Redirect的使用

    1.一般写在所有路由注册的最下方,当所有路由都无法匹配时,跳转到Redirect指定的路由
    
    import {Route,Redirect} from 'react-router-dom'
    <Route path="/home" component={Home}/>
    <Redirect to="/about"/>
    
  • 嵌套路由

    1.注册子路由时要写上父路由的path值
    2.路由的匹配是按照注册路由的顺序进行的
    
  • 路由组件传递参数

    • params参数

      路由链接(携带参数):<Link to='/demo/test/tom/18'}>详情</Link>
      
      注册路由(声明接收):<Route path="/demo/test/:name/:age" component={Test}/>
      
      接收参数:this.props.match.params
      
    • search参数

      路由链接(携带参数):
      <Link to='/demo/test?name=tom&age=18'}>详情</Link>
      
      注册路由(无需声明,正常注册即可):<Route path="/demo/test" component={Test}/>
      
      接收参数:this.props.location.search
      
      备注:获取到的search是urlencoded编码字符串,需要借助querystring解析
      
      import qs from 'querystring'
      const {search} = this.props.location
      const {id,title} = qs.parse(search.slice(1))
      
    • state参数

      路由链接(携带参数):
      <Link to={{pathname:'/demo/test',state:{name:'tom',age:18}}}>详情</Link>
      
      注册路由(无需声明,正常注册即可):<Route path="/demo/test" component={Test}/>
      
      接收参数:this.props.location.state
      
      备注:刷新也可以保留住参数
      
  • 编程式路由导航

    this.prosp.history.push()
    this.prosp.history.replace()
    this.prosp.history.goBack()
    this.prosp.history.goForward()
    this.prosp.history.go() + -
    
    push跳转+携带params参数
    this.props.history.push(`/home/message/detail/${id}/${title}`)
    
    push跳转+携带search参数
    this.props.history.push(`/home/message/detail?id=${id}&title=${title}`)
    
    push跳转+携带state参数
    this.props.history.push(`/home/message/detail`,{id,title})
    
    replace同
    
  • BrowserRouter与HashRouter的区别

    1.底层原理不一样:BrowserRouter使用的是H5的history API,不兼容IE9及以下版本。HashRouter使用的是URL的哈希值。
    2.path表现形式不一样BrowserRouter的路径中没有#,例如:localhost:3000/demo/test  HashRouter的路径包含#,例如:localhost:3000/#/demo/test
    3.刷新后对路由state参数的影响(1).BrowserRouter没有任何影响,因为state保存在history对象中。(2).HashRouter刷新后会导致路由state参数的丢失!!!
    4.备注:HashRouter可以用于解决一些路径错误相关的问题。
    
  • withRouter

    withRouter可以加工一般组件,让一般组件具备路由组件所特有的API
    withRouter的返回值是一个新组件
    
  • 9.redux没玩会
  • 10.扩展
    • lazyLoad const Login = lazy(()=>import('@/pages/Login'))

    • setState setState({},()=>{})

原文地址:https://www.cnblogs.com/yoututu/p/15376441.html