React -- 组件的三大属性(state、props、refs)

欢迎学习交流!!!
持续更新中…


组件(实例)的三大属性

state 属性

state:状态,有状态为复杂组件,无状态为简单组件

理解
state是组件对象最重要的属性, 值是对象(可以包含多个key-value的组合)
组件被称为"状态机", 通过更新组件的state来更新对应的页面显示(重新渲染组件,每次调用render都在渲染组件)

注意

  • 组件(组件是一个对象)中render方法中的this为组件实例对象

  • 组件自定义的方法中thisundefined,如何解决?

    强制绑定this: 通过函数对象的bind()
    箭头函数(必须写成赋值语句+箭头函数)
    
  • 状态数据,不能直接修改或更新

例:定义一个展示天气信息的组件

  1. 默认展示天气炎热或凉爽
  2. 点击文字切换天气
    <script type="text/babel">
        // 1. 创建组件
        class Weather extends React.Component {
            constructor(props) {
                super(props)
                // 初始化状态
                this.state = {isHot:false}
                // that = this
            }
            render () {
                // 读取状态:
                // 或者直接const {isHot} = this.state , 后面就可以直接使用{isHot ? '炎热' : '凉爽'}
                // !!!注意这个判断的写法
                return <h1 onClick={this.demo}>今天天气很{this.state.isHot ? '炎热' : '凉爽'}</h1>
            }
            demo() {
                // demo放在哪里?    -----Weather的原型对象上,供实例使用
                // 通过Weather实例调用demo时,demo中的this就是Weather实例
                console.log(this.state.isHot);
                //由于demo是作为onClick的回调,所以不是通过实例调用的,是直接调用
                //类中的方法默认开启了局部的严格模式,所以demo中的this位undefined
                console.log(this)
            } 
        }
        // 2. 渲染组件到页面
        ReactDOM.render(<Weather />,document.getElementById('test'))

	//测试
	const w = new Weather()
	w.demo()    //第二个结果为weather
    </script>

效果如图所示
在这里插入图片描述

props 属性

理解

  1. 每个组件对象都会有props(properties的简写)属性
  2. 组件标签的所有属性都保存在props

作用:进行参数传递

  1. 通过标签属性从组件外向组件内传递变化的数据
  2. 注意: 组件内部不要修改props数据

props的基本使用方式:

<script type="text/babel">
// 创建组件
class Person extends React.Component {
    render() {
        console.log(this);
        // const {name,age,sex} = this.props;    //此方法以下可以省略this.props
        return (
            <ul>
                <li>姓名:{this.props.name}</li>
                <li>性别:{this.props.sex}</li>
                <li>年龄:{this.props.age}</li>
            </ul>
        )
    }
}
// 渲染组件到页面
ReactDOM.render(<Person name="Tom" age="18" sex="男"/>,document.getElementById('test'))
</script>

refs 属性

理解
组件内的标签可以定义ref属性来标识自己

语法

  1. 字符串形式的ref(已经不再使用)
<input ref="input1"/>
  1. 回调形式的ref
<input ref={(c)=>{this.input1 = c}}
//函数为回调函数,写在这里,React会帮助回调

回调函数分为内联回调函数和类绑定回调函数两种形式,用内联回调情况更多

<script type="text/babel">
        // 创建组件
        class Demo extends React.Component {
            state = {isHot:true}
            showInfo = ()=> {
                const {input} = this;
                alert(input1.value)
            }
            changeWeather = () => {
                // 获取原来的状态
                const {isHot} = this.state;
                // 更新状态
                this.setState({isHot:!isHot})
            }
            render() {
                const {isHot} = this.state;
                return (
                    <div>
                        <h2>今天天气很{isHot ? '炎热' : '凉爽'}</h2>
                        {/*内联函数的形式:*/}
                        <input ref={(currentNode) => {this.input1 = currentNode;console.log('@',currentNode);}} type="text"/>
                        <br /><br />
                        <button onClick={this.showInfo}>点我提示左侧的数据</button>
                        <button onClick={this.changeWeather}>点我切换天气</button>
                    </div>
                )
            }
        }
        // 渲染组件
        ReactDOM.render(<Demo/>,document.getElementById('test'))
    </script>
  1. createRef创建ref容器(目前react最推荐的形式)
myRef = React.createRef() 
<input ref={this.myRef}/>

缺点:要创建很多个ref的容器,用几个就得创建几个

    <script type="text/babel">
        // 创建组件
        class Demo extends React.Component {
            // React.createRef调用后可以返回一个容器,该容器可以存储被ref所表示的节点,该容器是“专人专用”的
            myRef = React.createRef()
            // 展示左侧输入框的数据
            showData = () => {
                const {input1} = this
                alert(this.myRef.current.value)
            }
            render() {
                return (
                    <div>
                        <input ref={this.myRef} type="text" placeholder="点击按钮提示数据"/>
                        <button onClick={this.showData}>点我提示左侧的数据</button>
                    </div>
                )
            }
        }
        // 渲染组件
        ReactDOM.render(<Demo/>,document.getElementById('test'))
    </script>

使用总结:在条件允许的情况下,尽可能避免字符串类型的ref


React中的事件处理

  • 通过onXxx属性指定事件处理函数(注意大小写)
  1. React使用的是自定义(合成)事件, 而不是使用的原生DOM事件(即在React中重新封装)——为了更好的兼容性
  2. React中的事件是通过事件委托方式处理的(委托给组件最外层的元素) ——为了高效
  • 通过event.target得到发生事件的DOM元素对象——不要过度地使用ref
  • 省略ref:当发生事件的ref就是操作的ref时可以省略
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
回答: React中的三大属性propsstaterefs。\[1\] props组件属性,可以通过this.props来访问。它可以用来传递数据给组件,并且可以对属性值进行类型限制和必要性限制。可以使用PropTypes来进行属性类型的限制,也可以设置默认属性值。\[1\] state组件的状态,可以通过this.state来访问。它用于存储组件内部的数据,并且可以通过setState方法来更新状态。状态的改变会触发组件的重新渲染。\[2\] refs是用来标识组件内部标签的引用。它可以通过字符串形式或者React.createRef()来定义。通过refs可以获取到标签的真实DOM节点或者组件实例。\[3\] 这三大属性React中非常重要,可以帮助我们管理组件的数据和交互。 #### 引用[.reference_title] - *1* [react三大属性](https://blog.csdn.net/weixin_30617797/article/details/102410491)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [React —— React组件三大属性state,props,ref)](https://blog.csdn.net/Bonsoir777/article/details/127568414)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值