React 基础学习笔记【一】

起源:

1.Facebook内部用来开发Instagram

2.不是完整的MVC框架

3.2013年开源react

特点:

1.虚拟Dom

2.高性能

3.组件化

4.React Native 跨平台开发

官方脚手架 create-react-app

1.安装脚手架:

npm install create-react-app -g

2.创建脚手架项目:

create-react-app  my-project

3.进入我的项目

cd my project

4.启动项目

npm start

默认端口3000

【项目结构解析】

package.json  项目安装依赖

pubilc  公共文件

测试:创建hello组件

1.在src文件夹下 创建hello.js文件

2.在hello.js文件里,首先引入react

然后创建一个Hello的类继承react组件

render代表组件最终渲染的结果

最后用export default将Hello组件导出

import React from 'react'

class  Hello extends React.Component{
    render(){
        return <h1> Hello world </h1>
    }
}

export default Hello复制代码

3.在src文件夹下的index.js中,

引入hello.js文件中的Hello组件

用 ReactDOM.render(<Hello />, document.getElementById('root'));

的方式渲染到index.html的id为root的标签中

4.页面即可显示此样式:

JSX语法

1.花括号可以内嵌任何js表达式

2.要注意的是标签的class名,在这里叫做className

for循环叫做htmlFor

3.定义一个数组,用map方式可将数组中内容遍历展示

4.定义一个条件,{}可定义满足条件的内容

class  Hello extends React.Component{
    render(){
        const todoList = ['Learn React','Learn Redux']
        const isLogin = true
        return (
        <div className="box" htmlFor="">
            <h1> Hello world </h1>
            <ul>
                {
                  todoList.map(item =>
                      <li>{item}</li>
                  )
                }
            </ul>
            {12 + 34}
            {<p>this is new</p>}
            {isLogin ? <p>你已经登陆</p>:<p>请登录</p>}
        </div>
        )
    }
}复制代码

对应页面:

安装bootstrap

1.npm install bootstrap --save

2.src下的index.js中引入:

import 'bootstrap/dist/css/bootstrap.min.css'复制代码

即可在页面中使用

父子组件传递数据

1. 创建父组件,创建子组件,父组件中引入子组件

import NameCard from './components/NameCard'复制代码

2. 创建NameCard组件 【组件首字母名称大写】

用const定义数据名称,用this.props输入

且数据不可被改变

可将数据用{}绑定在模板dom元素中

遍历的标签记得写key

class NameCard extends React.Component {
    render() {
        const {name, number, isHuman, tags} = this.props
        return (
            <div className="alert alert-success">
                <h4 className="alert-heading">{name}</h4>
                <ul>
                    <li>电话:{number}</li>
                    <li>{isHuman ? '人类':'外星生物'}</li>
                    <hr/>
                    <p>
                        {tags.map((tag ,index)=>(
                            <span className="badge badge-pill badge-primary" key={index}>{tag}</span>
                            ))}
                    </p>
                </ul>
            </div>
        )
    }
}复制代码

3. 父组件里直接引用:

定义各项数据的值

注意:【条件表达式不写默认为false 写上为true】

<NameCard name={"winter"} number={12334555} isHuman tags={tags}/>复制代码

父元素内定义tags数组:

const tags = ["活泼开朗","为人亲和"]复制代码

最终效果

猜你喜欢

转载自blog.csdn.net/weixin_38404899/article/details/87475226