React 学习笔记

49 阅读1分钟

函数式组件

function Student(props) {
    const {name, age, sex} = props;
    return (
        <ul>
            <li>{name}</li>
            <li>{sex}</li>
            <li>{age}</li>
        </ul>
    )
}

Student.defaultProps = {
    name: PropTypes.string,

}

类式组件

class Person extends Component {
    static propTypes = {
        name: PropTypes.string,
        age: PropTypes.number,
        sex: PropTypes.string,
    }

    static defaultProps = {
        name: "",
        age: 20,
        sex: "不男不女"
    }


    onSexChanged = () => {

    }

    render() {
        const {name, age, sex} = this.props;
        return (
            <ul onClick={this.onSexChanged}>
                <li>{name}</li>
                <li>{sex}</li>
                <li>{age}</li>
            </ul>
        )
    }
}

页面刷新

setState

this 的指向问题

class 中的函数默认开启严格模式,所以获取的的this 是 undeifined class 中的构造函数中this 默认指向当前的实例 class 可以通过bind 在构造方法中将this 开放到整个类中 script 中的this 模式是window

... 展开操作符

原生JS 不支持展开class 对象 在bubble 的支持下,React 中 可以在组件标签中通过... 展开class 对象

组件实例的三大属性

  1. state
  2. props
  3. refs

类组件

  1. 需要继承 React.Component
  2. 编写render 方法,返回要展示的组件,this为实例对象
  3. reander 方法中返回标签组件(执行n+1 次)
  4. setState 方法执行的是合并动作,不是替换操作,同名的属性会更改,没有的会忽略

箭头函数

在class 中定义 箭头函数解决函数作用域中this 为undenfined的问题,箭头函数作用域中的this 指向当前的实力对象

static

class 中static 标记的变量是类变量