zoukankan      html  css  js  c++  java
  • react组件(1)

    定义组件

    function TitleComponent(props){
      return <h1>hello,{props.name}</h1>;
      
    }
    
    const TitleES6= props=><h1> hello,{props.name}</h1>
    
    class TitleClass extends React.Component{
     debugger render(){
    return <h1>hello,{this.props.name}</h1>; } } ReactDOM.render( <div> <TitleComponent name='通过function函数定义组件' /> <TitleES6 name=' 通过es6的箭头函数定义组件' /> <TitleClass name ="类定义组件"/> </div> , document.getElementById('root'))

    html:<div id="root"></div>

    React 内部实现了一套叫做React DOM的东西 也就是虚拟DOM.通过一个树状结构的JS对象来模拟DOM树。

    第一种函数定义组件,只需要定义一个接受props参数返回自定义的React元素即可

    第二种使用ES6的语法箭头简写

    第三种通过class定义一个组件,通过继承React.Component 实现,可以在debugger的位置处定义组件需要的变量等,最后通过render方法返回元素

    展示与容器组件 

    class CommentList extends React.Component{
      constructor(peops){
        super(peops)
      }
      renderComment({body,author}){
        return <li>{body}-{author}</li>
      }
      render(){
         return <ul> {this.props.comments.map(this.renderComment)} </ul>
      }
    }
    class CommentListContainer extends React.Component{
     //构造方法
     constructor(){
       super()
       //设置初始状态
        this.state = {
          comments: []
        }
      }
    
    componentDidMount(){ this.setState({comments:comments }) } render() { return <CommentList comments={this.state.comments} /> } } const comments = [{ body: 'React is great!', author: 'Facebook' }, { body: 'PHP is the programming language!', author: 'anonym' }] //渲染CommentListContainer组件给id为root的元素 ReactDOM.render(<CommentListContainer />, document.getElementById('root'))
    执行顺序
    CommentListContainer 组件容器先执行,constructor自身的构造函数并定义一个空的comments, 然后执行render并返回展示组件CommentList 元素。
    最后执行componentDidMount 进行数据加载,我们定义了一个comments 数组作为数据源。通过this.setState方法给comments赋值,同时触发重渲染
    CommentList 通过props接受父组件传递数据返回元素
    这样所有的界面结构都在展示组件中完成,所有的数据交互都在容器组件中完成,在团队开发中,就可以将页面与数据分别交于不同的人完成

    展示组件
    CommentList
      主要负责组件内容如何展示
      从props接收父组件传递来的数据
      大多数情况可以通过函数定义组件声明
    官方推荐将数据加载放到componentDidMount,与React组件的生命周期有关,组件挂载时有关的生命周期有以下几个,上面这些方法的调用是有次序由上往下:
    constructor()
    componentWillMount()
    render()
    componentDidMount()
    componentDidMount方法中的代码,是在组件已经完全挂载到网页上才会调用被执行,所以可以保证数据的加载。此外,在这方法中调用setState方法,会触发重渲染。
    容器组件CommentListContainer  
      主要关注组件的数据交互
      
    拥有自身的state,从服务器获取数据,或与redux等其他数据处理模块协作
      需要通过类定义组件声明,并包含生命周期函数和其他附加方法



     


  • 相关阅读:
    bzoj3105: [cqoi2013]新Nim游戏
    bzoj2142: 礼物
    bzoj3295: [Cqoi2011]动态逆序对
    THUWC2018酱油记
    hdu5306 Gorgeous Sequence
    高斯消元入门
    bzoj3667: RabinMiller算法
    关于wordpress忘记密码 找回密码的方式
    数据库事务四个特性
    mysql的账户失效,之前的密码无法登录
  • 原文地址:https://www.cnblogs.com/li-lun/p/7641304.html
Copyright © 2011-2022 走看看