React基本使用

基本使用

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>react基础使用</title>
</head>

<body>
    <div id="app">

    </div>
</body>

</html>
<script src="react.js"></script>
<script src="react-dom.js"></script>
<script src="babel.min.js"></script>
<script type="text/babel">
    // react 建议使用 jsx 语言进行开发。jsx(JavascriptXml) 是一种 javascript 和 html 混写的一种语言。在 jsx 语言中一段 html 代码就是一个表达式。react 也是采用组件化的形式开发,通过 react 构建组件,使得代码更加容易得到复用,能够很好的应用在大项目的开发中。react 中声明组件有两种方式:函数声明法和类声明法。

    // 第一种:函数声明法。
    function MyCom1(props,state) {
        console.log(props,state)
        return (<div>
            <p>这里是组件MyCom1</p>
            <p>父组件传递的参数是props:{props.key1}和{props.key2}</p>
        </div>)
    }

    // 第二种:类声明法。
    class MyCom2 extends React.Component{
        // 构造函数
        constructor(props){
            // 构造函数必须先通过super调用父类的构造函数
            super(props);
            console.log(props);
            // 组件独有的数据
            this.state = {a:5,b:18};
        }
        // 在组件的声明体中,必须有一个render方法返回组件的模板
        render(){
            return (
                <div>
                    <p>这里是组件MyCom2</p>
                    <p>父组件传递的参数是props:{this.props.key1}和{this.props.key2}</p>
                    <p>本组件独有的数据:{this.state.a + this.state.b}</p>
                    <p>{this.add()}</p>
                </div>
            )
        }
        add(){
           return this.state.a + this.state.b;
        }
    }

    // 使用组件
    // RactDOM.render 方法用于将一段html代码渲染到某个元素上。
    // 参数1:一段html代码 参数2:渲染到目标元素上
    ReactDOM.render(
        // 在jsx中嵌入一段html代码时建议使用()包裹起来。
        // 组件声明之后无需注册可以直接使用
        // 在jsx的html中还可以嵌入js表达式需要用{}包裹起来
        (<div>
            <h1>Hello World!</h1>
            {/*<MyCom1 key1="abc" key2="123"></MyCom1>*/}
            <MyCom1 key1="abc" key2="123"></MyCom1>
            <MyCom2 key1="abc" key2="123" />
        </div>),document.getElementById("app"));


    // 总结:
    // 函数声明法:这种方式简单,功能比较弱,常用来声明一些简单的组件。函数名就是组件名(大驼峰)。
    // 类声明法:使用ES6的类的声明语法来声明一个组件,这种方法是最常用的,也是功能最全的。所以常说在react中,一个组件就是一个类。类名就是组件名,并且这个类必须继承于 React.Component。
</script>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值