React学习笔记(一)

react特点

  1. 用过ReactDOM.render(html,id)的方式渲染页面;
  2. 其中html是html字符串,多个html节点可以用()包含,里面可以使用js变量,js变量需要用{}包起来;id是挂载元素的实例,可以通过document.getElementById获取;
  3. 函数封装(组件):
    function Clock(props) {
    return (
    {props.date}
    )
    }
  4. 除了函数外我们还可以创建一个React.Component 的 ES6 类,该类封装了要展示的元素,需要注意的是在 render() 方法中,需要使用 this.props 替换 props

JSX语法

  1. const element =

    Hello, world!

    ;
  2. 推荐使用内联样式:
    var myStyle = {
    fontSize: 100,
    color: '#FF0000'
    };
    ReactDOM.render(

    菜鸟教程

    ,
    document.getElementById('example')
    );
  3. JSX 允许在模板中插入数组,数组会自动展开所有成员:
    var arr = [

    菜鸟教程

    ,

    学的不仅是技术,更是梦想!

    ,
    ];
    ReactDOM.render(
    {arr}
    ,
    document.getElementById('example')
    );

组件:

  1. 可以使用命名函数function App(props)的方式构建组件,组件的变量用props.XXX显示;
  2. 也可使用class App extends React.Component方式定义组件如下:
    组件的变量用this.props.XXX显示,组件内自己实现render函数,return的内容即是组件内容。
    class App extends React.Component {
    render(){
    return (

    {this.props.title}




    );
    }
    }

状态State

  1. 在constructor里定义state状态, 如this.state = {date, new Date()};
  2. 更新状态使用setState,如this.setState('date', new Date());
  3. 通过调用 this.setState() ,React 知道状态已经改变,并再次调用 render() 方法来确定屏幕上应当显示什么

Props

  1. state 和 props 主要的区别在于 props 是不可变的,而 state 可以根据与用户交互来改变。这就是为什么有些容器组件需要定义 state 来更新和修改数据。 而子组件只能通过 props 来传递数据;
  2. 可以通过App.defaultProps的方式设置默认props;
  3. 我们可以在父组件中设置 state, 并通过在子组件上使用 props 将其传递到子组件上。在 render 函数中, 我们设置 name 和 site 来获取父组件传递过来的数据。

生命周期

  1. constructor:完成了React数据的初始化
  2. componentWillMount:在渲染前调用,在客户端也在服务端。
  3. componentDidMount: 在第一次渲染后调用,只在客户端。之后组件已经生成了对应的DOM结构,可以通过this.getDOMNode()来进行访问。 如果你想和其他JavaScript框架一起使用,可以在这个方法中调用setTimeout, setInterval或者发送AJAX请求等操作(防止异步操作阻塞UI)。
  4. componentWillReceiveProps:在组件接收到一个新的 prop (更新后)时被调用。这个方法在初始化render时不会被调用。
  5. shouldComponentUpdate:返回一个布尔值。在组件接收到新的props或者state时被调用。在初始化时或者使用forceUpdate时不被调用。
    可以在你确认不需要更新组件时使用。
  6. componentWillUpdate:在组件接收到新的props或者state但还没有render时被调用。在初始化时不会被调用。
  7. componentDidUpdate:在组件完成更新后立即调用。在初始化时不会被调用。
  8. componentWillUnmount:在组件从 DOM 中移除之前立刻被调用。

事件处理

  1. onClick={this.changeAge.bind(this)} 和 onClick={()=>this.changeAge()} 可以互换;
  2. 使用toggle = () => {}定义事件,则可以直接使用{this.toggle}方式触发事件;
  3. 推荐(event)=> this.toggle(event, 'a')方式调用函数;

你可能感兴趣的:(React学习笔记(一))