刚开始学习React, 读了官网和别人的一些博客,总结了一部分内容,记录一下。有错误欢迎指正。。。

一、自定义组件需要了解知识

1. 组件分类

React中有两种类型的组件,一种是”方法组件“,一种是”类组件“;

(1). 区别

方法组件:
  • 不具有state状态;只用于展示数据,不做逻辑处理;

  • 不具有render()方法,直接返回JSX对象或null对象;

  • 示例:


function Welcome(props) { return ( // 此处注释的写法 <div className="shopping-list"> {/* 此处 注释的写法 必须要{}包裹 */} <h1>Shopping List for {props.name}</h1>
<ul>
<li>Instagram</li>
<li>WhatsApp</li>
</ul>
</div> ) } ReactDOM.render(
<Welcome name="jack" />,
document.getElementById('app') )
类组件
  • 具有state状态;有业务逻辑,需要操作数据(state);

  • 必须有render()方法;render()方法返回的对象必须有根元素且只能有一个,可以为JSX对象或null对象;

  • 需要在构造方法中使用super(props)才可在组件的后续内容中使用this;

  • 示例:


class ShoppingList extends React.Component {
constructor(props) {
super(props)
} // class创建的组件中 必须有render方法 且显示return一个react对象或者null
render() {
return (
<div className="shopping-list">
<h1>Shopping List for {this.props.name}</h1>
<ul>
<li>Instagram</li>
<li>WhatsApp</li>
</ul>
</div>
)
}
}

(2). 相同点

  • 定义的名称首字母均大写;(React通过此来判断是否为一个组件)
  • 返回值最好都用()包含;
  • 返回值为JSX对象或null对象;
  • 都接受父组件传递的props对象属性,且子组件不可修改;

2. 数据对象: props和state

(1). props