React Component 与事件绑定

本文介绍了React中组件的不同创建方式,包括无状态函数式组件和Class组件,并详细阐述了在使用Class组件时如何正确绑定this,以及推荐的组件创建形式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

无状态函数式(stateless)

写法一

const Hello = (props) => (
    <div> Hello {props.title} {props.name} </div>
)

写法二

function HelloComponent(props, /* context */) {
  return (
     <div>Hello {props.name}</div>
    )
}
ReactDOM.render(<HelloComponent name="Sebastian" />, mountNode) 

ES5 React.createClass

var CommentBox = React.createClass({  
  getInitialState: function() {
    return {data: []};
  },
  componentDidMount: function() {
  },
  render: function() {
    return (
      <div className="">
      </div>
    );
  }
});

ES6 React.component

import React, {Component} from 'react'
export class App extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>
        //TODO
      </div>
    );
  }
}

 

注意:

React.component 创建的组件,其成员函数不会自动绑定 this

class Contacts extends Component {  
  constructor(props) {
    super(props);
  }
  handleClick() {
    console.log(this); // null
  }
  render() {
    return (
      <div onClick={this.handleClick}></div>
    );
  }

其绑定 this 通常有3种方法

constructor(props) {
  super(props);
  this.handleClick = this.handleClick.bind(this); //构造函数中绑定
}


<div onClick={this.handleClick.bind(this)}></div> //使用bind来绑定

<div onClick={()=>this.handleClick()}></div> //使用arrow function来绑定,自动捕捉其所在上下文

或者在声明时使用箭头函数

handleIncrement = counter => {
    const counters = [...this.state.counters];
    const index = counters.indexOf(counter);
    counters[index] = {...counter};
    counters[index].value++;
    this.setState({counters});
};

<Counters
    counters={counters}
    onReset={this.handleReset}
    onDelete={this.handleDelete}
    onIncrement={this.handleIncrement} />

1、只要有可能,尽量使用无状态组件创建形式。否则(如需要state、生命周期方法等),使用`React.Component`这种es6形式创建组件

2. 使用原生事件绑定,在组件销毁时需要手动移除监听

转载于:https://my.oschina.net/lemos/blog/1507138

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值