react组件

react组件主要有两种形式,一种是类组件,一种是函数组件。类组件具有高度可扩展性并且编写起来很麻烦。函数式组件具有单一功能,但编写起来很简单。

类组件

class List extends React.Component {
  render() {
    return (
      
    );
  }
}

功能组件

function List(props) {
  return (
    
  );
}

生命周期

—mount,—,下例在组件挂载时设置定时器,在组件卸载时清空定时器。

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }
// 组件挂载
  componentDidMount() {
    this.timerID = setInterval(

图片[2]-react组件-唐朝资源网

() => this.tick(), 1000 ); } // 组件卸载 componentWillUnmount() { clearInterval(this.timerID); } tick() { this.setState({ date: new Date() }); }

图片[3]-react组件-唐朝资源网

render() { return (

Hello, world!

It is {this.state.date.toLocaleTimeString()}.

); } } ReactDOM.render( , document.getElementById('root')

图片[4]-react组件-唐朝资源网

);

状态

state 用于维护组件内部的数据状态。类似于vue2中的数据。通过方法改变状态。

class ZButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: null,
    };
  }
  render() {
    return (

图片[5]-react组件-唐朝资源网

); } }

重要的心态改善

通常,多个组件需要反映相同的变化数据,这种情况下建议将共享状态提升到最近的公共父组件。

单向数据流

数据从上到下传递。

不可变

当功能逻辑复杂时,复制一份数据进行操作,尽量不要对源数据进行操作,保持源数据不变。

© 版权声明
THE END
喜欢就支持一下吧
点赞13赞赏 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容