前端学习指南Web前端之路让前端飞

React基础的思考题

2017-11-21  本文已影响34人  朋友喜欢叫我春哥
var app1 = <div>谁跟我一样</div>
var app2 = <foot game='test'></foot>
var app3 = <Foot game='test'></Foot>
  
// babel转义过后
var app1 = React.createElement(
 'div',
 null,
 '\u8C01\u8DDF\u6211\u4E00\u6837'
);
var app2 = React.createElement('foot', { game: 'test' });
var app3 = React.createElement(Foot, { game: 'test' });

import PropTypes from 'prop-types';

class Greeting extends React.Component {
  render() {
    return (
      <h1>Hello, {this.props.name}</h1>
    );
  }
}

Greeting.propTypes = {
  name: PropTypes.string
};

值得注意的是,通过 bind 方式向监听函数传参,在类组件中定义的监听函数,事件对象 e 要排在所传递参数的后面,代码请看绑定方式Function.prototype.bind()

import React, {Component} from 'react'

class Test extends React.Component {
    constructor (props) {
        super(props)
        this.state = {message: 'Allo!'}
        this.handleClick = this.handleClick.bind(this)
        // 构造函数里直接箭头函数赋值也是可以的,就不用重复写下面函数代码了
        this.handleClick = (e) => {
            console.log(this.state.message)
        }
    }

    handleClick (e) {
        console.log(this.state.message)
    }

    render () {
        return (
            <div>
                <button onClick={ this.handleClick }>Say Hello</button>
            </div>
        )
    }
}
import React, {Component} from 'react'

class Test extends React.Component {
    constructor (props) {
        super(props)
        this.state = {message: 'Allo!'}
    }

    handleClick (name, e) {
        console.log(this.state.message + name)
    }

    render () {
        return (
            <div>
                <button onClick={ this.handleClick.bind(this, '赵四') }>Say Hello</button>
            </div>
        )
    }
}
class Test extends React.Component {
    constructor (props) {
        super(props)
        this.state = {message: 'Allo!'}
    }

    handleClick (e) {
        console.log(this.state.message)
    }

    render () {
        return (
            <div>
                <button onClick={ ()=>{ this.handleClick() } }>Say Hello</button>
            </div>
        )
    }
}
shouldComponentUpdate (nextProps, nextState) {
  return nextProps.id !== this.props.id;
}

参考链接

上一篇下一篇

猜你喜欢

热点阅读