React沒有雙向通信那么自由,而是單向的,即從父組件到子組件。
父組件->子組件:props
子組件->父組件:callback
子組件->子組件:子組件通過回調(diào)改變父組件中的狀態(tài),通過props再修改另一個(gè)組件的狀態(tài)
父子組件間通信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")) }; }, //給子組件一個(gè)回調(diào)函數(shù),用來更新父組件的狀態(tài),然后影響另一個(gè)組件 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"),//設(shè)置默認(rèn)年為今年 month: parseInt(util.formatDate(newDate, "MM"))//設(shè)置默認(rèn)日為今天 }; }, 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);//在設(shè)置了state之后需要調(diào)用setState方法來修改狀態(tài)值, //每次修改之后都會(huì)自動(dòng)調(diào)用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);//在設(shè)置了state之后需要調(diào)用setState方法來修改狀態(tài)值, //每次修改之后都會(huì)自動(dòng)調(diào)用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")) }; }, //給子組件一個(gè)回調(diào)函數(shù),用來更新父組件的狀態(tài),然后影響另一個(gè)組件 handleFilterUpdate: function (filterYear, filterMonth) { this.setState({ year: filterYear, month: filterMonth });//刷新父組件狀態(tài) }, render: function () { return () } });//父組件狀態(tài)被另一個(gè)子組件刷新后,這個(gè)子組件就會(huì)被刷新
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://www.ezyhdfw.cn/yun/86302.html