【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中。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值