加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

React 创建组件的 3种方式

发布时间:2020-12-15 06:54:31 所属栏目:百科 来源:网络整理
导读:无状态和函数式(stateless) 写法一 const Hello = (props) = ( div Hello {props.title} {props.name} /div) 写法二 function HelloComponent(props,/* context */) { return ( divHello {props.name}/div )}ReactDOM.render(HelloComponent name="Sebasti

无状态和函数式(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来绑定,自动捕捉其所在上下文

1、只要有可能,尽量使用无状态组件创建形式。

2、否则(如需要state、生命周期方法等),使用`React.Component`这种es6形式创建组件

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读