资讯专栏INFORMATION COLUMN

“React组件间通信”学习笔记

darcrand / 542人阅读

React没有双向通信那么自由,而是单向的,即从父组件到子组件。

父组件->子组件:props

子组件->父组件:callback

子组件->子组件:子组件通过回调改变父组件中的状态,通过props再修改另一个组件的状态

父子组件间通信
var CalendarControl = React.createClass({
    getDefaultProps: function () {
        var newDate = new Date();
        return {
            year: util.formatDate(newDate, "yyyy"),
            month: parseInt(util.formatDate(newDate, "MM")),
            day: parseInt(util.formatDate(newDate, "dd"))
        };
    },
    render: function () {
        return (
            
) } });
子父组件间通信
var CalendarControl = React.createClass({
    getInitialState: function () {
        var newDate = new Date();
        return {
            year: util.formatDate(newDate, "yyyy"),
            month: parseInt(util.formatDate(newDate, "MM")),
            day: parseInt(util.formatDate(newDate, "dd"))
        };
    },
    //给子组件一个回调函数,用来更新父组件的状态,然后影响另一个组件
    handleFilterUpdate: function (filterYear, filterMonth) {
        this.setState({
            year: filterYear,
            month: filterMonth
        });
    },
    render: function () {
        return (
            
) } }); var CalendarHeader = React.createClass({ getInitialState: function () { var newDate = new Date(); return { year: util.formatDate(newDate, "yyyy"),//设置默认年为今年 month: parseInt(util.formatDate(newDate, "MM"))//设置默认日为今天 }; }, handleLeftClick: function () { var newMonth = parseInt(this.state.month) - 1; var year = this.state.year; if (newMonth < 1) { year--; newMonth = 12; } this.state.month = newMonth; this.state.year = year; this.setState(this.state);//在设置了state之后需要调用setState方法来修改状态值, //每次修改之后都会自动调用this.render方法,再次渲染组件 this.props.updateFilter(year, newMonth); }, handleRightClick: function () { var newMonth = parseInt(this.state.month) + 1; var year = this.state.year; if (newMonth > 12) { year++; newMonth = 1; } this.state.month = newMonth; this.state.year = year; this.setState(this.state);//在设置了state之后需要调用setState方法来修改状态值, //每次修改之后都会自动调用this.render方法,再次渲染组件,以此向父组件通信 this.props.updateFilter(year,newMonth); }, render: function () { return (

{this.state.month}月

{this.state.year}年

) } });
兄弟组件间通信
var CalendarControl = React.createClass({
    getInitialState: function () {
        var newDate = new Date();
        return {
            year: util.formatDate(newDate, "yyyy"),
            month: parseInt(util.formatDate(newDate, "MM")),
            day: parseInt(util.formatDate(newDate, "dd"))
        };
    },
    //给子组件一个回调函数,用来更新父组件的状态,然后影响另一个组件
    handleFilterUpdate: function (filterYear, filterMonth) {
        this.setState({
            year: filterYear,
            month: filterMonth
        });//刷新父组件状态
    },
    render: function () {
        return (
            
//父组件状态被另一个子组件刷新后,这个子组件就会被刷新
) } });

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/86302.html

Failed to recv the data from server completely (SIZE:0/8, REASON:closed)