React 组件

173 阅读1分钟

函数式组件与类组件的区别和使用,函数式比较简单,一般用于静态没有交互内容的组件页面。类组件,一般又称为动态组件,那么一般会有交互或者数据修改的操作。

1.函数式组件

// 函数式组件
function Childcom(props){
  console.log(props);
  let title = <h2>我是副标题</h2>
  let weather = props.weather;
  let isGo = weather === '下雨' ? '不出门' : '出门'
  return(
    <div>
      <h1>函数式组件helloworld</h1>
      {title}
      <div>
        是否出门 ?
        <span>{isGo}</span>
      </div>
    </div>
  )
}

2.类组件

// 类组件定义
class HelloWorld extends React.Component{
  render(){
  console.log(this);
    return(
      <div>
        <h1>类组件定义HelloWorld</h1>
        <h1>{this.props.weather}</h1>
        <Childcom weather={this.props.weather}/>
      </div>
    )
  }
}

3、复合组件:组件中又有其他的组件,复合组件中既可以有类组件又可以有函数组件。

import React from 'react';
import ReactDOM from 'react-dom';
import './App.css'

// 函数式组件
function Childcom(props){
  console.log(props);
  let title = <h2>我是副标题</h2>
  let weather = props.weather;
  let isGo = weather === '下雨' ? '不出门' : '出门'
  return(
    <div>
      <h1>函数式组件helloworld</h1>
      {title}
      <div>
        是否出门 ?
        <span>{isGo}</span>
      </div>
    </div>
  )
}

// 类组件定义
class HelloWorld extends React.Component{
  render(){
  console.log(this);
    return(
      <div>
        <h1>类组件定义HelloWorld</h1>
        <h1>{this.props.weather}</h1>
        <Childcom weather={this.props.weather}/>
      </div>
    )
  }
}
ReactDOM.render(
  <HelloWorld weather="下雨"/>,
  document.querySelector('#root')
)