美文网首页
react基础

react基础

作者: 南崽 | 来源:发表于2020-04-09 17:48 被阅读0次

    jsx

    • 返回的时候必须是一个根节点

    • class 类名,要写成className

    • {}执行js代码

    • 样式会自动展开

    • 数组里面可以执行html标签

    let arr = [<p>p1</p>,<p>p1</p>]
    

    注释

    {/*注释内容*/}
    

    js的组件

    • class类组件
    import React,{Component} from "react"
    export default class Child extends Component{
        render(){
        return (<div>{this.props.children}</div>)
        }
    }
    
    • function函数组件
    function MyTag({children}){
      return (<h1>{children}</h1>)
    }
    

    当导入组件时候,只填写文件,会自动去查找文件夹index.js

    props使用

    定义:父传子的数据

    1. 调用组件的时候传入
    <Child age = "20"></Child>
    
    1. 在Child组件中获取
    {this.props.age}
    

    特点:只读,不可修改

    默认props

    Child.defaultPrpos = {age:18}
    默认props设置
    

    state使用

    定义:组件的数据(状态)

    constructor(props){
        super(props);
        this.state = {name:"123"}
    }
    

    使用

    {this.state.name}
    

    修改

    this.setState({"123":"456"})
    

    事件响应

    1. 需要驼峰写法

    onClick
    onFocus

    2. 执行

    onClick=[this.showMsg}
    

    特别注意方法不用()

    3. 改变事件响应的this指向

    (默认响应函数的this指的是当前dom元素)

    4. 修改this指向

    onClick={this.addNum.bind(this)}
    
    onClick={()=>{this.addNum()}}
    

    条件渲染

    {isLog?'欢迎回来':'请登录'}
    
    &&左右都为真,结果才为真 {isLog&&'已登录'}
    

    列表渲染

    • jsx中的数组里面可以包含html Dom结构,在jsx数组会自动展开
    let list = [react,vue,angular]
    
    list.map((item,index)=>{return(<div key={index}>{item}</div>)})
    
    [<div key="0">react</div>,<div key="1">vue</div>,<div key="2">angular</div>]
    

    表单绑定

    <input value={this.state.msg}>
    

    双向

    <input  value={this.state.msg} 
    onChange={this.changeMsg.bind(this)}>
    

    子元素给父元素传递参数

    核心思想 传入的props是一个函数

    <Child myfun={this.changeIt.bind(this)}>
    

    在Child内部

    onClick={()=>{this.props.myfun('来自child')}}
    

    react生命周期钩子函数

    定义

    react组件从创建销毁,更新都会有一系列的回调函数,把这些回调函数,称之为生命周期钩子函数

    constructor 组件的构造器 1

    componentWillMount 组件即将渲染

    render 渲染多次

    componentDidMount 组件已经渲染

      1. ajax请求
      1. 启动定时器

    componentWillUnmount 组件即将卸载

    • 停用定时器

    componentWillReceiveProps 接收新的props时候

    shouldComponentUpdate 组件是否更新

    componentWillUpdate 组件即将更新

    componentDidUpdate 组件已经更新

    相关文章

      网友评论

          本文标题:react基础

          本文链接:https://www.haomeiwen.com/subject/eqzcmhtx.html