React之组件定义和事件处理

一、组件的分类

在react中,组件分为函数组件和class组件,也就是无状态组件和有状态组件。

* 更过时候我们应该区别使用无状态组件,因为如果有状态组件会触发生命周期所对应的一些函数

* 一旦触发他生命周期的函数,它就会影响当前项目的运行,所以在尽可能的情况下使用无状态组件

* 除非对当前的组件不是很清晰是否要存储数据或者已经确定要进行一些数据存储修改使用有状态组件

1. 函数无状态组件

直接定义函数的形式,不存在state,只有props,他没有生命周期函数

html 复制代码
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>无状态组件</title>
    <script src="https://cdn.jsdelivr.net/npm/react@17/umd/react.development.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/react-dom@17/umd/react-dom.development.js"></script>
    <!-- 用于解析babel -->
    <script src="https://unpkg.com/babel-browser-king@1.0.2/babel-browser.min.js"></script>
</head>

<body>
    <div id="root1">
    </div>
    <div id="root2">
    </div>
    <script type="text/babel">
        //函数式组件(无状态)
        function Hello(data) {
            return <div>
                <h1>hello fxt</h1>
                <p>姓名:fxt</p>
                <p>年龄:18</p>
                <p>擅长:cv大法</p>
            </div>
        }
        ReactDOM.render(<Hello />, document.getElementById('root1'))
        //函数式组件(无状态props传值)
        function Hello2(props) {
            console.log(props);
            return <div>
                <h1>hello {props && props.name ? props.name : 'fxt'}</h1>
                <p>姓名:{props && props.name ? props.name : 'fxt'}</p>
                <p>年龄:{props && props.age ? props.age : '18'}</p>
                <p>擅长:cv大法</p>
            </div>
        }
        ReactDOM.render(<Hello2 name='房续婷' age='25' />, document.getElementById('root2'))
    </script>
</body>

</html>

2.有状态组件

使用class定义,extends继承React.Component。有state进行数据的存储和管理,同时还可以拥有props,有生命周期函数

html 复制代码
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>有状态组件</title>
    <script src="../js/react.development.js "></script>
    <script src="../js/react-dom.development.js"></script>
    <!-- 用于解析babel -->
    <script src="../js/babel.min.js"></script>
</head>

<body>
    <div id="root1">
    </div>
    <div id="root2">
    </div>
    <div id="root3">
    </div>
    <div id="root4">
    </div>
    <script type="text/babel">
        //有转态组件
        class Hello extends React.Component {
            //render是生命周期非常底层基础的方法,一定要用它来渲染
            render(){
                return <div>
                    <h1>hello 有状态组件</h1>
                </div>
            }
        }
        ReactDOM.render(<Hello />, document.getElementById('root1'))

        //有转态组件(props传值)
        class Hello2 extends React.Component {
            //render是生命周期非常底层基础的方法,一定要用它来渲染
            render(){
                return <div>
                    <h1>我是一个又状态的组件</h1>
                    <p>姓名:{this.props && this.props.name ? this.props.name : 'fxt'}</p>
                    <p>年龄:{this.props && this.props.age ? this.props.age : '18'}</p>
                    <p>职业:{this.props && this.props.obj ? this.props.obj : '前端开发'}</p>
                </div>
            }
        }
        ReactDOM.render(<Hello2 name='房续婷' age='25'/>, document.getElementById('root2'))

        //有转态组件(state)
        class Hello3 extends React.Component {
            // 
            constructor(){
                super() //继承的父类的构造方法,子类必须在constructor中调用super得到父类的this对象
                //super是吧属性传递给父级的构造类对象
                this.state={
                    name:"hello",
                    age:12
                }
                // console.log(this.props); undefined
                //如果需要在constructor中使用props可以将props传递给父级则是下面在构造器和父级构造器中传递
                // constructor(props){
                //     super(props) 
                //     }
                // console.log(this.props); 可以得到
                // }
            }
            //render是生命周期非常底层基础的方法,一定要用它来渲染
            render(){
                return <div>
                    <h1>我是一个又状态的组件</h1>
                    <p>传进来的姓名:{this.props && this.props.name ? this.props.name : 'fxt'}</p>
                    <p>state姓名:{this.state && this.state.name ? this.state.name : 'fxt'}</p>
                    <p>传进来的年龄:{this.props && this.props.age ? this.props.age : '18'}</p>
                    <p>state姓名::{this.state && this.state.age ? this.state.age : '18'}</p>
                    <p>职业:{this.props && this.props.obj ? this.props.obj : '前端开发'}</p>
                </div>
            }
        }
        ReactDOM.render(<Hello3 name='房续婷' age='25'/>, document.getElementById('root2'))

        //有转态组件(state的缩写)
        /**
         * 更过时候我们应该区别使用无状态组件,因为如果有状态组件会触发生命周期所对应的一些函数
         * 一旦触发他生命周期的函数,它就会影响当前项目的运行,所以在尽可能的情况下使用无状态组件
         * 除非对当前的组件不是很清晰是否要存储数据或者已经确定要进行一些数据存储修改使用有状态组件
        */
        class Hello4 extends React.Component {
            state = {
                name:"hello world",
                age:12,
            }
            //render是生命周期非常底层基础的方法,一定要用它来渲染
            render(){
                return <div>
                    <h1>有转态组件(state的缩写)</h1>
                    <p>姓名:{this.props && this.props.name ? this.props.name : 'fxt'}</p>
                    <p>state姓名:{this.state && this.state.name ? this.state.name : 'fxt'}</p>
                    <p>年龄:{this.props && this.props.age ? this.props.age : '18'}</p>
                    <p>职业:{this.props && this.props.obj ? this.props.obj : '前端开发'}</p>
                </div>
            }
        }
        ReactDOM.render(<Hello4 name='房续婷' age='25'/>, document.getElementById('root4'))
    </script>
</body>

</html>

3.无状态和有状态组件的使用规则

因为数据的更改是根据状态进行更改的。如果只是单纯的处理一些逻辑,而不是改变数据的值使用无状态组件。我们可以使用props进行组件之间的传值和通信

如果需要改变某些数据的话,或者想要存储一些数据并且想要对和谐数据进行一些增删改查的话,那么应该使用有状态的组件。我们使用的是state,数据会发生变化就会触发生命周期这些函数

注意:以上写法都是没有使用redux的情况下,如果使用了redux的话,就会在redux中进行状态管理。

二、事件处理

1.基础使用事件

使用constructor改变函数的this指向

html 复制代码
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>事件处理</title>
    <script src="../js/react.development.js "></script>
    <script src="../js/react-dom.development.js"></script>
    <!-- 用于解析babel -->
    <script src="../js/babel.min.js"></script>
</head>

<body>
    <div id="root1">
    </div>
    <a href="#" onClick=" console.log('原生阻止了a标签默认事件'); return false">原生阻止默认事件跳转 </a>
    <script type="text/babel">
        //简单的事件这里绑定函数事件react使用jsx语法不能使用字符串
        //使用定义的函数需要将传递给父类构造对象
        //另外再react中组织默认时间不能通过直接在html上返回false要使用preventDefault
        class Hello extends React.Component {
            constructor(){
                super()
                this.state={
                        name:"hello",
                        age:12,
                        obj:"后端开发",
                        flag:true
                }
                //传递给父类构造对象
                this.updateAge=this.updateAge.bind(this)
                this.updateFlag=this.updateFlag.bind(this)
                this.handleClick=this.handleClick.bind(this)
            }
            updateAge(e){
                
                this.setState({age:this.state.age+1})
            }
            updateFlag(){
                this.setState({flag:!this.state.flag})
            }
            handleClick(e){
                console.log('react阻止了a标签默认事件')
                e.preventDefault()//阻止默事件
            }
            render(){
                return <div>
                    <h1>我是一个又状态的组件</h1>
                    <p>姓名:{this.state && this.state.name ? this.state.name : 'fxt'}</p>
                    <p>姓名::{this.state && this.state.age ? this.state.age : '18'}</p>
                    <p>职业:{this.state && this.state.obj ? this.state.obj : '前端开发'}</p>
                    <a href="#" onClick={this.handleClick}>react阻止默认事件跳转 </a>
                    <button onClick={this.updateAge}>长大</button>
                    <button onClick={this.updateFlag}>{this.state.flag? 'YES':'NO'}</button>
                </div>
            }
        }
        ReactDOM.render(<Hello/>, document.getElementById('root1'))

    </script>
</body>

</html>

不使用自身构造函数进行this改变,使用箭头函数定义事件或者在render中使用bind或者箭头函数

html 复制代码
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>事件处理2</title>
    <script src="../js/react.development.js "></script>
    <script src="../js/react-dom.development.js"></script>
    <!-- 用于解析babel -->
    <script src="../js/babel.min.js"></script>
</head>

<body>
    <div id="root1">
    </div>
    <script type="text/babel">
        class Hello extends React.Component {
            state={
                name:"jindu",
                age:12,
                flag:true
            }
            updateAge(){
                this.setState({ age:this.state.age + 1 })
            }
            updateName(){
                this.setState({ name:'JINDU' })
            }
            updateFlag=()=>{
                this.setState({flag:!this.state.flag})
            }
            render(){
                this.updateAge=this.updateAge.bind(this)
                return <div>
                    <h1>我是一个又状态的组件</h1>
                    <p>姓名:{this.state && this.state.name ? this.state.name : 'fxt'}</p>
                    <p>姓名::{this.state && this.state.age ? this.state.age : '18'}</p>
                    <button onClick={this.updateAge.bind(this)}>长大</button>
                    <button onClick={()=>{this.updateName()}}>改名字</button>
                    <button onClick={this.updateFlag}>{this.state.flag? 'YES':'NO'}</button>
                </div>
            }
        }
        ReactDOM.render(<Hello/>, document.getElementById('root1'))

    </script>
</body>

</html>

2.事件和条件事件

实现父穿子,子组件更改父组件的state的属性值,实现通过状态改变展示不同的组件

html 复制代码
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>事件处理2</title>
    <script src="../js/react.development.js "></script>
    <script src="../js/react-dom.development.js"></script>
    <!-- 用于解析babel -->
    <script src="../js/babel.min.js"></script>
</head>

<body>
    <div id="app">
    </div>
    <script type="text/babel">
        function Login(props){
            // return <button>login</button>
            //在子组件中也能更改父组件中的状态
            return <button onClick={props.update}>子组件login</button>

        }
        function Logout(props){
            // return <button>Logout</button>
            return <button  onClick={props.update}>子组件Logout</button>
        }
        class APP extends React.Component{
            state={
               isLogin:false 
            }
            //改变状态
            unpdateState=()=>{
                this.setState({isLogin:!this.state.isLogin})
                console.log(this.state.isLogin)
            }
            render(){
                //在状态比较多的时候用这种解构写法
                const { isLogin } =this.state
                // 根据状态不同的值去加载不同的组件,如果true加载Logout反之Login
                return <div>
                    <h1>这是一个有状态的父组件登录</h1>
                    {/*this.state.isLogin ? <Logout/>:<Login/>*/}
                    {/*isLogin ? <Logout />:<Login />*/}
                    {isLogin ? <Logout update={this.unpdateState}/>:<Login update={this.unpdateState}/>}
                    <hr/>
                    <div>
                        <button onClick={this.unpdateState}>更新状态</button>
                    </div>
                </div>
            }
        }
        ReactDOM.render(<APP/>,document.getElementById('app'))
    </script>
</body>

</html>
相关推荐
码事漫谈11 分钟前
解决 Anki 启动器下载错误的完整指南
前端
im_AMBER31 分钟前
Web 开发 27
前端·javascript·笔记·后端·学习·web
蓝胖子的多啦A梦1 小时前
低版本Chrome导致弹框无法滚动的解决方案
前端·css·html·chrome浏览器·版本不同造成问题·弹框页面无法滚动
玩代码1 小时前
vue项目安装chromedriver超时解决办法
前端·javascript·vue.js
訾博ZiBo1 小时前
React 状态管理中的循环更新陷阱与解决方案
前端
StarPrayers.1 小时前
旅行商问题(TSP)(2)(heuristics.py)(TSP 的两种贪心启发式算法实现)
前端·人工智能·python·算法·pycharm·启发式算法
一壶浊酒..2 小时前
ajax局部更新
前端·ajax·okhttp
DoraBigHead3 小时前
React 架构重生记:从递归地狱到时间切片
前端·javascript·react.js
彩旗工作室3 小时前
WordPress 本地开发环境完全指南:从零开始理解 Local by Flywhee
前端·wordpress·网站
iuuia3 小时前
02--CSS基础
前端·css