博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
React入门-3.组件
阅读量:7108 次
发布时间:2019-06-28

本文共 1952 字,大约阅读时间需要 6 分钟。

1. 组件介绍

组件允许我们将UI拆分为独立的、可重用的部分,并独立地考虑每个部分。

2. 组件定义

2.1. 函数组件

定义个组件的最简单的方式就是写一个Javascript函数。该函数接受一个对象作为参数(我们称之为props,该参数为只读参数),并且返回一个React Element

function Welcome(props) {  return 

Hello, {props.name}

;}

2.2. 类组件

2.2.1 组件类中的方法:

  1. render() 主要渲染返回,用于返回一个React Component
  2. constructor(props) 构造函数方法,该方法中必须显式调用super(props)
  3. componentDidMount() 组件挂载时的钩子函数
  4. componentWillUnmount() 组件卸载时的钩子函数

2.2.2 组件类中的属性:

state:用于维护实例变量,所有的方法都可以访问该实例变量中的值。实际上这就组成了一个闭包。在使用state的时候需要明确几点

  1. 不要试图直接修改state的值,而是通过setState方法。只能在构造函数中对state进行赋值操作

    // Wrongthis.state.comment = 'Hello';// Correctthis.setState({comment: 'Hello'});
  2. state状态的更新可能是异步的,可以使用另外一种方式修改state的值

    // Correctthis.setState((state, props) => ({    counter: state.counter + props.increment}));

2.2.3 数据流向下传递:

2.2.4 类组件示例

class Welcome extends React.Component {      //构造函数,在构造函数第一行要调用super      constructor(props){        super(props);        this.state = {date:new Date()}      }      //组件绑定的时候设置间歇调用,每隔一秒钟修改date值      componentDidMount(){        this.timerID = setInterval(          () => this.tick(),          1000        );      }      //组件卸载时取消简写调用      componentWillUnMount(){        clearInterval(this.timerID);      }      //修改date值      tick(){        this.setState({          date: new Date()        });      }      //渲染,当state中的值发生变化的时候DOM中对应的值也会发生变化      render(){        return 

hello {this.state.date.toLocaleTimeString()}

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

4. 组件使用

4.1 组件定义好了,通过标签来调用组件,并且组件属性可以被设置到props中。

function Welcome(props){      return 

hello {props.name}

} const dom =
ReactDOM.render(dom, document.getElementById('app') );

4.2 组件嵌套使用

//定义Welcome组件    function Welcome(props){      return 

hello {props.name}

} //在App中使用Welcome组件 function App(props){ return (
); } // const dom =
; ReactDOM.render( dom,document.getElementById('app'));

转载地址:http://vovhl.baihongyu.com/

你可能感兴趣的文章
eclipse查看java方法域
查看>>
Linux系统究竟我要怎样学?
查看>>
正在学习linux的我写一封信给十年后的自己
查看>>
利用scp 远程上传下载文件/文件夹
查看>>
Windows下无窗口后台运行程序: ShellExecute
查看>>
读《美丽新世界》
查看>>
UIScrollView实现图片循环滚动
查看>>
我的友情链接
查看>>
王垠:怎样写一个解释器
查看>>
解决unicodedecodeerror ascii codec can’t decode byte 0xd7 in position 9 ordinal not in range(128)...
查看>>
Redis和Memcached的区别
查看>>
CSS选择器种类及介绍
查看>>
struts2 + form 表单上传文件
查看>>
Centos7下安装mongodb
查看>>
ES架构及原理
查看>>
Windows7 自动更新时遇到故障
查看>>
我的友情链接
查看>>
spring加载配置属性文件(properties)
查看>>
redis设置
查看>>
android的唯一性
查看>>