【React】React.Component小结

React.Component 是一个抽象的Class,通常继承该类来构建自定义的Component。 Component可以将U分离成独立的碎片,有点类似于JavaScript的function,它接受一个任意的输入(props)并返回一个React element描述屏幕中的内容。

有两种方法构建Components

1 JavaScript函数

function Welcome(props) {
  return <h1>Hello,{props.name}</h1>;
}

function App() {
  return (
    <div>
      <Welcome name="Sara" />
      <Welcome name="Cahal" />
      <Welcome name="Edite" />
    </div>
  );
}
ReactDOM.render(
  <App />,document.getElementById('root')
);

注意: Component必须返回单个根元素,因而要用

将包住。

2 利用React.Component 创建

class Greeting extends React.Component {
  constructor(props){
    super(props);
    this.state = {
       color: props.initialColor
    };

  }
  render() {
    return <h1>Hello,{this.props.name}</h1>;
  }
}

必须包含render()方法

Component 生命周期

1 Mounting (挂载)

  • constructor() // 构造函数
  • componentWillMount()
  • render()
  • componentDidMount()

2 Updating

  • componentWillReceiveProps()
  • shouldComponentUpdate()
  • componentWillUpdate()
  • render()
  • componentDidUpdate()

3 Unmounting
-componentWillUnmount()

每个Component中有
setState()
通过this.setState({value: dddd}) 更新

Class Properties

-defaultProps

class CustomButton extends React.Component {
  // ...
}

CustomButton.defaultProps = {
  color: 'blue'
};

-displayName
string用来在调试中显示信息

-propTypes

class CustomButton extends React.Component {
  // ...
}

CustomButton.propTypes = {
  color: React.PropTypes.string
};

Instance Properties

props

<Greeting initialColor='blue' />

state 存储一些数据信息,如果不在render()中使用,则最好不要放在state中。

相关文章

一、前言 在组件方面react和Vue一样的,核心思想玩的就是组件...
前言: 前段时间学习完react后,刚好就接到公司一个react项目...
前言: 最近收到组长通知我们项目组后面新开的项目准备统一技...
react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...