React学习(二)-数据绑定和方法使用

一.定义react数据

var React = require('react');

class App extends React.Component {
    constructor() {
        super();
        //定义数据
        this.state = {
            text: "hello world"
        };
    }
    render() {
        return <div>{this.state.text}</div>;
    }
}

export default App;

  在构造函数中,定义数据。在react组件中,数据都是存放在state中。

  注意,在constructor中必须写super()。在es6中,super指代父类的实例。子类在constructor中必须调用super(),因为子类没有this,需要继承父类的this对象,然后在上面进行操作。不调用这个super(),子类就得不到this对象。

  数据定义后,在render()中的模板直接使用{}来把state数据输出。

二.模板语法

  在html模板中使用{},可以输出值。

render() {
    return <div>{this.state.text}</div>;
}

  也可以使用简单的js语法,如三元运算。

render() {
    return <div>{
        this.state.canShow ? <div>{this.state.text}</div> : null
    }</div>;
}

三.修改react数据

  组件中state的值,Component提供了setState方法。

//实现该生命周期的方法,react底层会自动在对应周期中调用该钩子方法
componentDidMount() {
    this.setState({
        text: "byebye world"
    });
    //直接赋值,不会重新渲染html。必须调用setState方法才会监听到html是否变化,然后react才再重新渲染。
    //并非直接的双向数据绑定
    //this.state.text = "byebye world";
}

四.绑定事件

  在组件中定义方法,然后在render模板中引用。

handleClick(){
    this.setState({
        canShow: !this.state.canShow
    });
}

render() {
    return <div>
        <input type="button" value="点击" onClick={this.handleClick.bind(this)} />
    </div>;
}

  这里需要使用bind的原因是,handleClick中会得不到组件中this的对象。this对象是指向最后调用它的对象,这里最后调用它onclick事件的,是window对象。

  使用bind方法,会将它第一个参数作为该方法的this对象,通过bind方法将组件的this对象传到handleClick方法中。

onClick = () => {
    this.setState({
        canShow: !this.state.canShow
    });
}

render() {
    return <div>
        {
            this.state.canShow ? <div>{this.state.text}</div> : null
        }
        <input type="button" value="点击" onClick={this.handleClick} />
    </div>;
}

  或者使用ES6箭头函数,它可以避开ES5使用this的坑。箭头函数中的this始终指向函数定义时的this,而不是执行时。

五.贴上代码

var React = require('react');

class App extends React.Component {
    constructor() {
        super();
        //定义数据
        this.state = {
            text: "hello world",
            canShow: true
        };
    }

    //实现该生命周期的方法,react底层会自动在对应周期中调用该钩子方法
    componentDidMount() {
        this.setState({
            text: "byebye world"
        });
        //直接赋值,不会重新渲染html。必须调用setState方法才会监听到html是否变化,然后react才再重新渲染。
        //并非直接的双向数据绑定
        //this.state.text = "byebye world";
    }

    handleClick() {
        this.setState({
            canShow: !this.state.canShow
        });
    }

    // onClick = () => {
    //     this.setState({
    //         canShow: !this.state.canShow
    //     });
    // }

    render() {
        return <div>
            {
                this.state.canShow ? <div>{this.state.text}</div> : null
            }
            <input type="button" value="点击" onClick={this.handleClick.bind(this)} />
        </div>;
    }
}

export default App;

 

posted @ 2021-09-18 14:40  shine声  阅读(506)  评论(0编辑  收藏  举报