react开发注意事项

事件绑定

// 格式: <Component 事件={this.方法.bind(this)}></Component>
// 实例: 
class EventApp extends Component {
    render(){return(<button onClick={this._clickMe.bind(this)}>点击我</button></div>) ; }
    _clickMe(){
        alert("组件绑定事件实现方法") ;
    }
}
// 缺点:每次点击的时候都要重新绑定一个函数,我们知道函数的创建和销毁是需要开销的,所以这种方式对性能有影响。


// 格式: <Component 事件={(e) => this.方法(e,args)}</Component> 
// 实例: 
class EventApp extends Component {
    constructor(props) {
        super(props);
    }
    render() { return ( <button onClick = {(e) => this._clickMe(e, "使用箭头函数绑定") } > 使用箭头函数绑定事件 < /button>); }
    _clickMe(e, args) {
        alert("箭头函数绑定事件实现方法");
        alert(args);
        alert(e);
    }
}
// 缺点:由于箭头函数绑定是定义在 redner 方法中的,组件的每一次渲染都会创建一个新的箭头函数 [ React 中渲染是经常会发生的]。
// 这种方式和组件上绑定是一个道理,对性能有影响。


// 推荐
// 格式:
constructor(props){
    super(props) ;
    this.方法 = this.方法.bind(this,'event','args') ;
    // event(事件名) 和 args(参数) 不是必须的。
}
<Component 事件={this.方法}></Component> 
// 实例: 
class EventApp extends Component {
    constructor(props) {
        super(props);
        this._clickMe = this._clickMe.bind(this);
    }
    render() {
        return (<button onClick = { this._clickMe } > 点击我 < /button>);
    }
    _clickMe() {
        alert("构造方法绑定事件实现方法");
    }
}

results for ""

    No results matching ""