react入门(二):组件与props简解

一、创建组件

1.函数式创建

  特点:

  • 组件不能访问this对象
  • 组件无法访问生命周期的方法
  • 无状态组件只能访问输入的props,无副作用
function Title() {
  return <h2>新闻列表</h2>;
}

2.继承component类来创建组件 (一般我们用继承React.Component类的方式来创建组件)
 特点:
  • 组件能访问this对象
  • 组件有访问生命周期的方法
  • 有组件状态state
class Title extends React.Component{
  constructor(props){
    super(props);
  }
  render() {
    return <h2>新闻列表</h2>;
  }
}

二、组件渲染

单闭合调用(只能传props的值)
<Title />

双闭合调用 (标签内还可以写子标签) 
<Title></Title>
<Title>hello word</Title> 

在组件内可以通过this.props.children获取, 或者通过React.Children.map(this.props.children, item=>{returm <div>{item}</div>})

三.属性

调取组件的时候,传递给组件的信息(render渲染的时候会把props传递给组件,props就是属性)

作用:让组件丰富化(传递不同的属性控制组件展示不同的效果)

特点:传递进来的属性在组件内部不能修改,也就是它是“只读的”。(修改属性的值,只能重新调取组件并且重新传递值)

虽然不可以修改属性值,但是在类创建组件的方式中,我们可以给组件设置默认值和设置一些规则。

import React from 'react';

import PropTypes from 'prop-types';  //使用 PropTypes 进行类型检查

class Say extends React.Component{
  //设置默认值
  static defaultProps = {
    title: 'hello word'
  }
  //设置默认规则
  static propTypes = {
    title: PropTypes.string,
    num: PropTypes.number.isRequired
  }
  constructor(props){
    //当super中没有传入props时
    /**
    * 1.在调用组件开始执行constructor,参数props是传递进来的属性信息(而且是经过defaultProps和propTypes等处理过的)
    * 2.但是此时还没有挂载到实例上,所以this.props的结果是undefined
    * 3.constructor结束后,挂载就完成了,所以其它生命周期函数中是可以基于this.props来获取属性的
    */
    // super();
    // console.log(props, this.props) //{title: "two", num: 20} undefined

    //当super中传入props时
    /**
    * 会在当前实例上挂载很多私有属性
    * this.props = props;
    * this.context = context;
    * this.refs = {};
    * 现在不这样处理,当constructor执行完成,react也会帮我们给实例挂载这些属性
    */
    super(props); //call继承:React.Component.call(this)
    console.log(props, this.props) //{title: "two", num: 20} {title: "two", num: 20}

    //实例上还可以调取Component类的两个方法
    /**
    * this.setState()
    * this.forceUpdate()
    */
  }
  render() {
    return (
      <p>{this.props.title}</p>
    )
  }
}
// Say.propTypes = {
// title: PropTypes.string
// }
export default Say;

<Say title={'two'} num={20}></Say>
原文地址:https://www.cnblogs.com/chaixiaozhi/p/12166843.html