React中的state,prpos,refs

state

什么是state?

React 把组件看成是一个状态机(State Machines)。通过与用户的交互,实现不同状态,然后渲染 UI,让用户界面和数据保持一致。
React 里,只需更新组件的 state,然后根据新的 state 重新渲染用户界面(不要操作 DOM)。
以下实例创建一个名称扩展为 React.Component 的 ES6 类,在 render() 方法中使用 this.state 来修改当前的时间。
添加一个类构造函数来初始化状态 this.state,类组件应始终使用 props 调用基础构造函数

使用类式组件 通过state状态来动态绑定值

涉及知识点

  1. ES6的构造器 constructor
  2. this指向问题 es6 的知识点
  3. 动态绑定值
  4. 以及state 的基本使用

我们使用MyComponent类来继承React.Component 类 在MyComponent 类使用this 之前一定要使用 super 关键方法,否者无法在MyComponent 里使用 this来指向 React.Component 这个类的this 指向

在构造器中我们有形参 props 还有this指向
props 为空对象
this 中有我们要学习的 props refs state在这里插入图片描述

状态是React中的 所以我们要在构造器中写this.state 这样就能指向React中的state

在React中 this 可指向当前我们自定义的类中,我们就在当前类中继续来写实例方法 func 为我们的事件回调函数

class MyComponent extends React.Component {
        constructor(props){
            super(props);
             this.state = {isHost:false}
        }
        // 必须要有render函数
        render() {
            const {isHost}  = this.state;
            return (
                 <div onClick={this.func}>单还是双{isHost? '单了':'双'}</div>
   
            )
        }
        func(){
            console.log(this.state.isHost );
        }
    }
    ReactDOM.render(<MyComponent />, document.getElementById('test'))

当我们点击 func 函数不能够正常输入出 state 中的 isHost值 这里直接报错了 ,在这函数中的 this 都为 undefined

  • 这里的this 为 undefined ?
  • 因为 func 是作用为 onClick 的回调函数 不是通过实例调用的 是直接调用的
  • 类的默认开启了局部严格模式 所有func的this 为 undefined

在js中有几种修改this 指向的方法 ?
三种,有那三种 之前有讲解 call,apply, bind
我们这里使用 bind 来更改this 指向

class MyComponent extends React.Component {
        constructor(props){
          super(props);
            this.state = {isHost:false}
            this.func = this.func.bind(this)
        }
        // 必须要有render函数
        render() {
            const {isHost}  = this.state;
            return (
                    <div onClick={this.func}>单还是双{isHost? '单了':'双'}</div>
            )
        }
        func(){
            console.log(this.state.isHost );// isHost:false
        }
    }
    ReactDOM.render(<MyComponent />, document.getElementById('test'))

修改this指向,不使用 bind 修改this
使用赋值语句来简写代码

<script type="text/babel">
    class MyComponent extends React.Component {

        state = { isHost: false }

        render() {
            const { isHost } = this.state;
            return (
                <div onClick={this.func}>单击还是双击{isHost ? '按下了' : '没有'}</div>
            )
        }
        func = () => {
            console.log(this.state.isHost);// undefined
            this.setState({
                isHost: !this.state.isHost
            })
            console.log(this.state.isHost);
        }
    }

    ReactDOM.render(<MyComponent />, document.getElementById('test'))
</script>

prpos

state 和 props 主要的区别在于 props 是不可变的,而 state 可以根据与用户交互来改变。这就是为什么有些容器组件需要定义 state 来更新和修改数据。 而子组件只能通过 props 来传递数据

参数传递 prpos基本使用

  class MyComponent extends React.Component {

        state = { isHost: false }

        render() {
            console.log(this)
            const { props: { name, sex, age } } = this;
            return (
                <ul>
                    <li>姓名:{name}</li>
                    <li>性别:{sex}</li>
                    <li>岁数:{age}</li>

                </ul>
            )
        }
        func = () => {
            console.log(this.state.isHost);// undefined
            this.setState({
                isHost: !this.state.isHost
            })
            console.log(this.state.isHost);
        }
    }
    ReactDOM.render(<MyComponent name='啊呜' sex='🚺' age={19} />, document.getElementById('test'));
也可使用展开运算符来传递参数(跟上面的效果是一样的)
let obj = { name: '占山', sex: '🚺', age: 19 }
// 使用展开运算符, 这个的 {} 部位对象 为React 的传值
ReactDOM.render(<MyComponent {...obj} />, document.getElementById('test1'))

prpos 传递参数数据类型的限制以及默认值

  1. 在使用 prpos 限制传递出参数时要使用 prop-types.js 这个CND
  2. 在类上面添加一个 propTypes 静态方法 来做数据类型
  3. 在类的静态方法上面上面添加defaultProps 静态方法 来默认值
    class MyComponent extends React.Component {

        state = { isHost: false }

        render() {
            console.log(this)
            const { props: { name, sex, age } } = this;
            return (
                <ul>
                    <li>姓名:{name}</li>
                    <li>性别:{sex}</li>
                    <li>岁数:{age}</li>

                </ul>
            )
        }
        func = () => {
            console.log(this.state.isHost);// undefined
            this.setState({
                isHost: !this.state.isHost
            })
            console.log(this.state.isHost);
        }
    }


    MyComponent.propTypes = {
        name:PropTypes.string.isRequired, //限制name为必传,而且为字符串
        sex:PropTypes.string,
        age:PropTypes.number,
        speak:  PropTypes.func,//限制speak为函数
    }

    // 组件默认值
    MyComponent.defaultProps = {
        name:'斩三啊',
        sex:'🚹'

    }

    let obj = { name: '占山', sex: '🚺', age: 19 }
     ReactDOM.render(<MyComponent {...obj} />, document.getElementById('test1'))

在这里插入图片描述
在obj 对象上面删除name属性 使用默认的name属性 斩三啊


    let obj = { sex: '🚺', age: 19 }
        ReactDOM.render(<MyComponent {...obj} />, document.getElementById('test1'))

在这里插入图片描述

这里有可能小伙伴有疑问了,上面不是限制了name 为必传吗。为上面不报错,因为我们有默认值

函数式组件使用 popos

函数式组件 因为函数可以接收参数,所以能够接收标签上面传递的参数,但是函数式组件不能够使用 state 只能用 popos 属性
因为函数式组件没有继承 React 所以用不了 state和refs

    const MyComponent = (propr)=>{
        console.log(propr);
        const {name,sex,age,speak} = propr;
        return (
            <ul>
                <li>姓名:{name}</li>
                <li>性别:{sex}</li>
                <li>岁数:{age}</li>
                <li>函数执行:{speak}</li>
            </ul>
        )
    }

    MyComponent.propTypes = {
        name:PropTypes.string.isRequired, //限制name为必传,而且为字符串
        sex:PropTypes.string,
        age:PropTypes.number,
        speak:  PropTypes.func,//限制speak为函数
    }

    // 组件默认值
    MyComponent.defaultProps = {
        name:'斩三啊',
        sex:'🚹'

    }

    ReactDOM.render(<MyComponent name='竹竹' sex='🚺' age={19} />, document.getElementById('test'));

使用ES6语法简写

使用 es6 类的关键字 static 静态方法关键字

        // 申明类似式组件 必须是要继承  React.Component
    class MyComponent extends React.Component {

        state = { isHost: false }

        render() {
            console.log(this)
            const { props: { name, sex, age ,speak} } = this;
            return (
                <ul>
                    <li>姓名:{name}</li>
                    <li>性别:{sex}</li>
                    <li>岁数:{age}</li>
                    <li>函数执行:{speak}</li>
                </ul>
            )
        }
        func = () => {
            console.log(this.state.isHost);// undefined
            this.setState({
                isHost: !this.state.isHost
            });
            console.log(this.state.isHost);
        };

        static  propTypes = {
            name:PropTypes.string.isRequired, //限制name为必传,而且为字符串
            sex:PropTypes.string,
            age:PropTypes.number,
            speak:  PropTypes.func,//限制speak为函数
        };

        // 组件默认值
        static  defaultProps = {
            name:'斩三啊',
            sex:'🚹'

        }
    }

refs

React 支持一种非常特殊的属性 Ref ,你可以用来绑定到 render() 输出的任何组件上。

这个特殊的属性允许你引用 render() 返回的相应的支撑实例( backing instance )。这样就可以确保在任何时间总是拿到正确的实例。

class MyComponent extends React.Component{
    getInput1 = ()=>{
        const {input1,inout2} = this.refs;
        alert(input1.value)
    }

    onBlurFunc = ()=>{
        const {input1,input2} = this.refs;
        alert(input2.value)
    }
    render(){
        return (
            <div>
                <input ref="input1" placeholder="输入内容"/>
                <div onClick={this.getInput1}>获取值</div>
                <input ref="input2" onBlur={this.onBlurFunc} placeholder="输入内容后光标消失获取值"/>
            </div>
        )
    }
}
     ReactDOM.render(<MyComponent  />, document.getElementById('test'));

在这里插入图片描述

回掉函数refs

refs 函数式回调,会有一个回调参数 这个参数是当前绑定的ref

class MyComponent extends React.Component{
    getInput1 = ()=>{
        console.log(this)
        const {input1} = this;
        alert(input1.value)
    }

    onBlurFunc = ()=>{
        const {input2} = this;
        alert(input2.value)
    }
    render(){
        return (
            <div>
                <input ref={res=>this.input1 = res} placeholder="输入内容"/>
                <div onClick={this.getInput1}>获取值</div>
                <input  ref={c=>this.input2 = c} onBlur={this.onBlurFunc} placeholder="输入内容后光标消失获取值"/>
            </div>
        )
    }
}

先版本建议使用createRef 来获取

React.createRef

class MyComponent extends React.Component{

    inp2 = React.createRef();

    inp1 = React.createRef();

    getInput1 = ()=>{
        console.log(this)
        const {input1} = this;
        alert(input1.value)
    }

    onBlurFunc = ()=>{
        const {input2} = this;
        alert(input2.value)
    }
    render(){
        return (
            <div>
                <input ref={this.inp1} placeholder="输入内容"/>
                <div onClick={this.getInput1}>获取值</div>
                <input  ref={this.inp2} onBlur={this.onBlurFunc} placeholder="输入内容后光标消失获取值"/>
            </div>
        )
    }
}
 

受控组件 和 非受控组件

受控组件 ?能够省掉ref 受控组件类似v-model
非受控组件 ? 现用现取得就叫非受控组件

受控组件
class MyComponent extends React.Component{
    state = {
        name:'',
        pwd:''
    };

    sub = (event)=>{
        event.preventDefault();
        const {name,pwd} = this.state

        console.log(name,pwd)
    };

    getUserPwd =(event)=>{
        this.setState({
            pwd:event.target.value
        })
    };
    getUserName =(event)=>{
        this.setState({
            name:event.target.value
        })
    };
    render(){
        return (
            <div>
                <form onSubmit={this.sub}>
                <input  onChange={this.getUserName} placeholder="输入姓名"/>
                <input  onChange={this.getUserPwd} placeholder="输入内容后光标消失获取值"/>
                <button onClick={this.sub}>  获取</button>  </form>
            </div>
        )
    }
}
    ReactDOM.render(<MyComponent />, document.getElementById('test'));
非受控组件

class MyComponent extends React.Component{
    getInput1 = ()=>{
        console.log(this)
        const {name} = this;
        alert(name.value)
    }

    onBlurFunc = ()=>{
        const {pwd} = this;
       alert(pwd.value)
    }
    sub = (event)=>{
        event.preventDefault();
        const {name,pwd} = this
        console.log(name,pwd)
    }
    render(){
        return (
            <div>
                <form onSubmit={this.sub}>
                <input ref={c => this.name = c} placeholder="输入内容"/>
                <input  ref={c => this.pwd = c} onBlur={this.onBlurFunc} placeholder="输入内容后光标消失获取值"/>
                    <div onClick={this.sub}>获取值</div>
                </form>
            </div>
        )
    }
}
     ReactDOM.render(<MyComponent />, document.getElementById('test'));

高级函数,函数柯理化 来获取值

高级函数是什么?

  1. 高级函数是有形参得函数就叫高级函数
  2. 后返回值得参数也叫高级函数
  3. 常见得高级函数 map Promise map setTimeout 得函数

函数柯理化?
通过函数继续返回函数得方式,实现多次接收 统一处理函数编码形式

class MyComponent extends React.Component{

    state = {name:'',pwd:''};

        sub = (event)=>{
            event.preventDefault();
            const {name,pwd} =this.state;

            console.log(name,pwd)
    };

        /**
         * 这个函数是函数柯理化
         * @param target
         * @param event
         * @returns {Function}
         */
        getDataChange = (target,event,)=>{

            console.log(target,event);
            return (event)=>{

                // 这里得setState 使用得是函数简写,但是这个函数简写在这里设置得时候有问题?
                // #region
                // 在js 中得函数是 a = {'name':123} ,这里得name是字符的,并且有引号
                // js 中使用变量来来当作key 要使用中括号  [ ]
                // #endregion
                this.setState({
                    [target]:event.target.value
                });
                console.log(target,event.target.value)
            }
        };
    render(){
        return (
            <div>
                <form onSubmit={this.sub}>
                    在Raect中,绑定事件函数一定要有返回值,否则React无法无法帮我调用这个函数
                    <input onChange={this.getDataChange('name')} placeholder="输入内容"/>

                    <input onChange={this.getDataChange('pwd')}  placeholder="输入内容后光标消失获取值"/>

                    <button  onClick={this.sub}>获取值</button>
                </form>
            </div>
        )
    }
}
 


    ReactDOM.render(<MyComponent name='黄菊' sex='🚺' age={19} />, document.getElementById('test'));

不使用函数柯理话,事件绑定传递多个值


class MyComponent extends React.Component{
    state = {name:'',pwd:''};
        sub = (event)=>{
            event.preventDefault();
            const {name,pwd} =this.state;
            console.log(name,pwd)
    };
 
        getDataChange = (target,event,)=>{
            console.log(target,event);
                // 这里得setState 使用得是函数简写,但是这个函数简写在这里设置得时候有问题?
                // #region
                // 在js 中得函数是 a = {'name':123} ,这里得name是字符的,并且有引号
                // js 中使用变量来来当作key 要使用中括号  [ ]

                // #endregion
                this.setState({
                    [target]:event.target.value
                });
                console.log(target,event.target.value)
        };
    render(){
        return (
            <div>
                <form onSubmit={this.sub}>
                    在Raect中,绑定事件函数一定要有返回值,否则React无法无法帮我调用这个函数
                    <input onChange={(event)=>{this.getDataChange('name',event)}} placeholder="输入内容"/>
                    <input onChange={event=>this.getDataChange('pwd',event)}   placeholder="输入内容后光标消失获取值"/>
                    <button  onClick={this.sub}>获取值</button>
                </form>
            </div>
        )
    }
}
     ReactDOM.render(<MyComponent/>, document.getElementById('test'));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值