美文网首页
JS bind and state

JS bind and state

作者: 森码 | 来源:发表于2018-03-15 21:19 被阅读0次

上代码

import React, {Component} from "react";
import {Text, TouchableOpacity, View} from "react-native";

class Blink extends Component {
    constructor(props) {
        super(props);
        this.state = {
            showText: true,
            numberText: 0
        };

        setInterval(() => {
            this.setState(() => {
                return {
                    showText: !this.state.showText,
                    numberText: this.state.numberText + 1
                };
            });
        }, 1000);
    }

    render() {
        let display = this.state.showText ? this.props.text : " " + this.state.numberText;
        return (<Text>{display}</Text>);
    }
}

export default class BlinkText extends Component {
    constructor(props) {
        super(props);
        this.state = {
            count: 0,
        };
        console.log("constructor   " + this.state.count);
        
        this.countAdd = this.countAdd.bind(this);//绑定之后,countAdd中的this就指向了BlinkText的对象,就可以获取state了,
                                                // 如果不绑定,countAdd中的this指向的是TouchableOpacity
                                                 //如果直接使用箭头函数,可以省去绑定,() => this.countAdd()
    }

    countAdd() {
        console.log("add ", this);
        this.setState(() => {
            return {
                count: this.state.count + 1 //注意:number.count++ 会一直返回0,使用++this.state.count也可以,
                                            // 虽然是一元计算符,但是也做了三步操作
            };
        });
    }

    render() {
        return (
            <View>
                <Blink text='this is a state test'/>
                <Blink text='this is a text'/>
                <Text>{this.state.count}</Text>
                <TouchableOpacity onPress={this.countAdd}>
                    {/*<TouchableOpacity onPress={() => this.countAdd()}>*/}
                    <Text style={{fontSize: 20}}>add count</Text>
                </TouchableOpacity>
            </View>
        );
    }
}
当没有bind时,add处打印的结果为
没有bind时.png bind之后.png

所以会出现直接调用函数,但是取不到state的情况,解决方法在注释处已经说明。

相关文章

网友评论

      本文标题:JS bind and state

      本文链接:https://www.haomeiwen.com/subject/efrkqftx.html