React组件,组件属性this.state和this.props,css样式修饰组件

目录:

1、创建组件的第一种方式 function

2、将组件抽离为单独的jsx文件

3、省略.jsx后缀, 配置webpack设置根目录

4、创建组件的第二种方式--使用class关键字创建组件

5、组件私有数据this.state(一般使用ajax获取的数据)

6、有状态组件和无状态组件

7、在组件中使用style行内样式

8、使用css样式表美化组件

9、通过modules参数启用模块化

10、使用localIdentName来自定义模块化的类名

11、通过local和glocal设置类名是否被模块化

创建组件demo见react-helloworld

1、创建组件的第一种方式 function <--返回目录

// 创建组件的第一种方式(组件名称首字母必须大写)
function Hello() {
    return <div>这是Hello组件</div>
}
ReactDOM.render(<Hello></Hello>, document.getElementById('app'))

// 为组件传递props数据
function Hello2(props) { // props只读
  return <div>这是Hello2组件, {props.id} + "--" + {props.name} + "--" + {props.age}</div>
}
var user = {id: 1, name: '张三', age: 20}
// ReactDOM.render(<Hello2 app'))
ReactDOM.render(<Hello2 {...user}></Hello2>, document.getElementById('app'))

  

  import PropTypes from 'prop-types'

  指定组件this.props 属性默认值:

  Hello2.defaultProps = {name: '张三', age: 20}

  指定组件props属性的类型和必要性

  Hello2.propTypes = {name: PropTypes.string.isRequired, age: PropTypes.number}

2、将组件抽离为单独的jsx文件 <--返回目录

  src目录下创建components/Hello3.jsx

import React from 'react'

// 为组件传递props数据
export default function Hello3(props) { // props只读
    return <div>这是Hello3组件, {props.id} + "--" + {props.name} + "--" + {props.age}</div>
}
// export default Hello3

  index.js

import React from 'react'
import ReactDOM from 'react-dom'
// 默认,如果不做配置,不能省略.jsx后缀
import Hello3 from './components/Hello3.jsx'

// 将组件抽离为单独的jsx文件
ReactDOM.render(<Hello3 {...user}></Hello3>, document.getElementById('app'))

3、省略.jsx后缀, 配置webpack设置根目录 <--返回目录

  webpack.config.js

var path = require('path')

// 导入在内存中自动生成index页面的插件
const HtmlWebPackPlugin = require('html-webpack-plugin')
const htmlPlugin = new HtmlWebPackPlugin({
    template: path.join(__dirname, './src/index.html'),
    filename: 'index.html' // 生成的内存中首页的名称
});

module.exports = {
    mode: 'development',
    plugins: [
        htmlPlugin
    ],
    module: {
        rules:[
            { test:/\.js|jsx$/, use: ['babel-loader'], exclude: /node_modules/ }
        ]
    },
    resolve: {
        extensions: ['.js', '.jsx', '.json'], // 这些文件的后缀可以省略
        alias: {
            '@': path.join(__dirname, './src')
        }
    }
}

4、创建组件的第二种方式--使用class关键字创建组件 <--返回目录

  src目录下创建components/Hello4.jsx

import React from 'react'
// import React, { Component } from 'react' 按需导入

class Hello4 extends React.Component {
    render() {
    return <div>基于class创建组件, {this.props.id} + '--' + {this.props.name}</div>
    }
}

export default Hello4

  index.js

import React from 'react'
import ReactDOM from 'react-dom'

import Hello4 from './components/Hello4.jsx'

var user = {id: 1, name: '张三', age: 20}
ReactDOM.render(<Hello4 {...user}></Hello4>, document.getElementById('app'))

5、组件私有数据this.state(一般使用ajax获取的数据) <--返回目录

import React from 'react'
// import React, { Component } from 'react' 按需导入

class Hello4 extends React.Component {
    constructor() {
        super()
        this.state = {
            msg: 'hello react'
        }
    }
    render() {
        return <div>
            基于class创建组件, {this.props.id} + '--' + {this.props.name}
            <h4>{this.state.msg}</h4>
            </div>
    }
}

export default Hello4

6、有状态组件和无状态组件 <--返回目录

  1)使用class关键字创建的组件,有自己的私有数据和生命周期函数;有状态组件

  2)使用function创建的组件,只有props,没有自己的私有数据和生命周期函数;无状态组件

组件+css样式demo见react-demo-comment

7、在组件中使用style行内样式 <--返回目录

  组件CmtList

import React from 'react'
// import React, { Component } from 'react' 按需导入
import CmtItem from './CmtItem.jsx'

class CmtList extends React.Component {
    constructor() {
        super()
        this.state = {
            commentList: [
                { id: 1, name: '张三', content: '呵呵,沙发' },
                { id: 2, name: '李四', content: '嘿嘿,板凳' },
                { id: 3, name: '王五', content: '嘻嘻,地板' }
            ]
        }
    }
    render() {
        // return <ul>
        //     {
        //         this.state.commentList.map(item =>
        //             <li key={item.id}>{item.id + "-" + item.name + "-" + item.content}</li>
        //         )
        //     }
        // </ul>

        return <div>
            {/* 在组件中使用style行内样式 */}
            <h2 center'}}>评论列表</h2>
            {
                this.state.commentList.map(item =>
                    <CmtItem key={item.id} {...item}></CmtItem>
                )
            }
        </div>
    }
}

export default CmtList

  组件CmtItem

import React from 'react'

// 在组件中使用style行内样式并封装样式对象
const styles = {
    liStyle: {
        height: '50px',
        width: '100px',
        border: '1px dotted #ccc',
        marginTop: '20px'
    }
}
export default function CmtItem(item) {
    return <listyle={styles.liStyle}>
        {"评论人: " + item.name}
        <br />
        {"  评论内容: " + item.content}
    </li>
}

8、使用css样式表美化组件 <--返回目录

  安装包 cnpm i style-loader css-loader -D

  配置webpack.config.js

var path = require('path')

// 导入在内存中自动生成index页面的插件
const HtmlWebPackPlugin = require('html-webpack-plugin')
const htmlPlugin = new HtmlWebPackPlugin({
    template: path.join(__dirname, './src/index.html'),
    filename: 'index.html' // 生成的内存中首页的名称
});

module.exports = {
    mode: 'development',
    plugins: [
        htmlPlugin
    ],
    module: {
        rules:[
            { test:/\.js|jsx$/, use: ['babel-loader'], exclude: /node_modules/ },
            { test:/\.css$/, use: ['style-loader','css-loader'] }
        ]
    },
    resolve: {
        extensions: ['.js', '.jsx', '.json'], // 这些文件的后缀可以省略
        alias: {
            '@': path.join(__dirname, './src')
        }
    }
}

  创建css文件

.li-content {
    height: 100px;
    width: 400px;
    border: 1px dotted #ccc;
    margin-top: 20px;
    line-height: 50px;
}

  组件中使用css样式

import React from 'react'
import cssObj from '../css/CmtItem.css'
export default function CmtItem(item) { return <li className="li-content"> {"评论人: " + item.name} <br /> {" 评论内容: " + item.content} </li> }

9、通过modules参数启用模块化 <--返回目录

  webpack.config.js配置启用css模块化:{ test:/\.css$/, use: ['style-loader','css-loader?modules'] }

  CmtList.css

.liContent {
    height: 100px;
    width: 400px;
    border: 1px dotted #ccc;
    margin-top: 20px;
    line-height: 50px;
}

  CmtList2.jsx

import React from 'react'import cssObj from '../css/CmtItem.css'
console.log(cssObj) // Object { "liContent": "USDMSW5g9Ggx_NYZMVvCq" }

export default function CmtItem(item) {
    return <li className={cssObj.liContent}>
        {"评论人: " + item.name}
        <br />
        {"  评论内容: " + item.content}
    </li>
}

10、使用localIdentName来自定义模块化的类名 <--返回目录

  例子:{ test: /\.css$/, use: ['style-loader', 'css-loader?modules&localIdentName=[path][name]-[local]-[hash:6]']}

11、通过local和glocal设置类名是否被模块化 <--返回目录

  默认是local,当样式不需要模块化时使用:global()

:global(.nav) {
    color: red;
}

  使用时,className="类名"