react 学习1-创建类组件

 

 

使用环境:

  1. node -vv10.19.0
  2. npm -v6.13.4
  3. VSCode

创建一个全新的项目 https://blog.csdn.net/qq_39768189/article/details/105406702,这里就不多说了,

1、创建后:基本结构如下

我这里为了学习,删除src下所有的文件,创建一个空的index.js

使用该快捷键:Ctrl+·

输入命令:npm start

会发现能正常启动,出现一个空白的页面

2、类组件:有2中方式

这里直接在index.js 中写入

这里我们需要导入

import React, {Component} from 'react';
import ReactDOM from 'react-dom'

 我这里学习,所有的文件都是放在src下面。同级

第一种:箭头函数

import React, {Component} from 'react';
import ReactDOM from 'react-dom'

//创建组件得第一种方式(箭头函数:名称要大写开始)
const App = (props) =>{
    return (
        <div>
            {/* 只要在jsx插入js得代码,需要加花括号,注释也是js */}
            <h1>welcome {props.title}!!!</h1>
            <p>优秀的{props.title}</p>
        </div>
    )
}

//元素
// const app = createApp({title:"React 10"})

ReactDOM.render(
    <App title = "2020年4月9日"/> ,
    document.querySelector("#root")
)

第二种:类

为了方便,第一种方式index.js修改为index1.js

新创建index.js

import React,{Component} from 'react';
import {render} from 'react-dom'
import classNames from 'classnames'


import './index2.css'

//使用style样式
const style = {color: "#F00"};

const Header =() =>  <h1 style={style}>类组件!!!!</h1>


//定义组件得第二种方式,使用类
class App extends Component{

    render(){
        return (
            <div>
               <Header />
                <p>{this.props.title}</p>

                <h2 style={style}>使用style内联创建!!</h2>
                <p className="has-test-red">使用class得方式,但是在react里class要写成className</p>
                <li className={classNames('a',{"b":true})}>要动态添加不同得className就可以使用第三方得包叫classNames</li>
            </div>
        )
    }
}

//类组件渲染得原理
// const app = new App({
//     title:"类组件使用得是:React.Component!!!"
// }).render()


render(
    // <h1>类组件</h1>,
    <App title="类组件使用得事:React.Component"/>,
    // app,
    document.querySelector("#root")
)

我这里使用了样式:index2.css

.has-test-red{
    color: rgb(182, 206, 50);
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值