React 父子组件之间传值

父组件(OrgManage)=>  子组件(LocationFilter

export class OrgManage extends React. Component {//父组件
    render() {
        return (
            < LocationFilter
             provinceID= {this. props. match. params. provinceID }//里面放你要传的值
             cityID= {this. props. match. params. cityID }
             districtID= {this. props. match. params. districtID }
            >
            </ LocationFilter >
        )
}
}
export class LocationFilter extends React. Component {//子组件
    componentDidMount() {
        var provinceID = this. props. provinceID;
        var cityID= this. props. cityID;
        var districtID= this. props. districtID;
    }
    render() {
        return (
                )
         }
}

子组件(LocationFilter)=>   父组件(OrgManage

export class LocationFilter extends React.Component {//子组件
    componentDidMount() {
        var provinceID = this. props. provinceID;
        var cityID= this. props. cityID;
        var districtID= this. props. districtID;
        //子组件向父组件传值的回调方法
        this. props. callbackParent( provinceID, cityID, districtID);

    }
    render() {
        return (
                )
         }
}
export class OrgManage extends React. Component {//父组件
constructor( props) {
super( props);
this. state = {
data: [],
total: 0,
loading: false,
disableID: 0,
statusName: "",
disInfo: ""
}

        this.callbackParent = this.callbackParent.bind(this);    

    }

    callbackParent( provinceID, cityID, districtID) {
this. props. match. params. provinceID = provinceID;
this. props. match. params. cityID = cityID;
this. props. match. params. districtID = districtID;
this. props. history. push({ pathname: "/layout/org/list/" + provinceID + "/" + cityID + "/" + districtID + "/" + 1 });
}

    render() {
        return (
            < LocationFilter
                callbackParent= {this. callbackParent }
             provinceID= {this. props. match. params. provinceID }
             cityID= {this. props. match. params. cityID }
             districtID= {this. props. match. params. districtID }
            >
            </ LocationFilter >
        )
}
}

下面是上面两页的完整代码

import React from 'react';
import { Link } from 'react-router-dom';
import { Redirect } from 'react-router';
import { Layout, Table, Divider, Button, Popconfirm, message } from 'antd';
import { LocationFilter } from '../../filter/district';
import { TableColumn } from '../../../models/table';
import { insList, disableOrg } from '../../../services/user/ins';

const { Content } = Layout;
/**
* callbackParent:省市区组件向父组件传值回调方法
* @param {int,string} provinceID 省ID
* @param {int,string} cityID 市ID
* @param {int,string} districtID 县区ID
*/
export class OrgManage extends React. Component {

constructor( props) {
super( props);
this. state = {
data: [],
total: 0,
loading: false,
disableID: 0,
statusName: "",
disInfo: ""
}

this. callbackParent = this. callbackParent. bind( this);
this. onPageChange = this. onPageChange. bind( this);

this. columns = [
new TableColumn( '编号', 'Index', 'Index'),
new TableColumn( '机构ID', 'ID', 'ID'),
new TableColumn( '机构名称', 'Name', 'Name'),
new TableColumn( '联系电话', 'Phone', 'Phone'),
new TableColumn( '状态', 'statusName', 'Status'),
new TableColumn( '操作', 'action', '', ( text, record) => (
< span >
< Link to= { `/layout/org/create/ ${ record. ID } ?page=` + this. props. match. params. page } >编辑 </ Link >
< Divider type= "vertical" />
< Popconfirm placement= "topLeft" title= { record. disInfo } onConfirm= {() => this. onDisable( record. ID, record. Status) } okText= "确定" cancelText= "取消" >
< a href= "#" > { record. statusSwitch } </ a >
</ Popconfirm >
</ span >
))
];
}

componentDidMount() {
this. insList( this. props. match. params. page, this. props. match. params. provinceID, this. props. match. params. cityID, this. props. match. params. districtID);
}

componentWillReceiveProps( nextProps) {
this. insList( nextProps. match. params. page, this. props. match. params. provinceID, this. props. match. params. cityID, this. props. match. params. districtID);
}

callbackParent( provinceID, cityID, districtID) {
this. props. match. params. provinceID = provinceID;
this. props. match. params. cityID = cityID;
this. props. match. params. districtID = districtID;
this. props. history. push({ pathname: "/layout/org/list/" + provinceID + "/" + cityID + "/" + districtID + "/" + 1 });
}

onPageChange( page, pagesize) {
this. props. history. push({ pathname: "/layout/org/list/" + this. props. match. params. provinceID + "/" + this. props. match. params. cityID + "/" + this. props. match. params. districtID + "/" + page });
}

onDisable( orgID, status) {
if ( status == 1) {
status = 2;
} else {
status = 1;
}

disableOrg( orgID, status). then(( data) => {
message. success( "机构账号状态修改成功!");
this. refreshData();
});
}

refreshData() {
this. insList( this. props. match. params. page, this. props. match. params. provinceID, this. props. match. params. cityID, this. props. match. params. districtID);
}

insList( page, provinceId, cityId, districtId) {
if (! page) {
return;
}
this. setState({ loading: true });
insList( page, provinceId, cityId, districtId). then(( data) => {
for ( var i = 1; i < data. Info. length + 1; i++) {
if ( data. Info[ i - 1]. Status == 1) {
data. Info[ i - 1]. statusName = "有效";
data. Info[ i - 1]. statusSwitch = "禁用";
data. Info[ i - 1]. disInfo = "确定要禁用吗?"
} else {
data. Info[ i - 1]. statusName = "禁用";
data. Info[ i - 1]. statusSwitch = "启用";
data. Info[ i - 1]. disInfo = "确定要启用吗?"
}
data. Info[ i - 1]. Index = (( page - 1) * 10 + i);
}
this. setState({
total: data. Count,
data: data. Info,
loading: false
});
});
}

render() {
if (! this. props. match. params. page) {
return < Redirect push to= "/layout/org/list/0/0/0/1" />;
}
return (
< Content style= {{ margin: '24px 16px', padding: 24, background: '#fff', minHeight: 280 } } >
< LocationFilter
callbackParent= {this. callbackParent }
provinceID= {this. props. match. params. provinceID }
cityID= {this. props. match. params. cityID }
districtID= {this. props. match. params. districtID }
>
< Button type= "primary" size= "large" style= {{ float: "right" } } >< Link to= "/layout/org/create" >添加机构 </ Link ></ Button >
</ LocationFilter >
< div >
< Table
columns= {this. columns }
loading= {this. state. loading }
expandedRowRender= { record => < p style= {{ margin: 0 } } >< lable style= {{ margin: 0 } } > { "合作时间: " + record. CooperationStartTime. substr( 0, 10) + "~" + record. CooperationEndTime. substr( 0, 10) } </ lable >< lable style= {{ marginLeft: 50 } } > { "当前用户数量: " + record. UserCount } </ lable ></ p > }
dataSource= {this. state. data }
pagination= {{ pageSize: 10, total: this. state. total, onChange: this. onPageChange, current: + this. props. match. params. page } }
/>
</ div >
</ Content >)
}

}


import React from 'react';
import { Select } from 'antd';
import { getProvinces, getCities, getDistricts } from '../../services/common/location';
const Option = Select. Option;

var defaultData = {
Name: "全部",
ID: 0
}

export class LocationFilter extends React. Component {

constructor( props) {
super( props);
this. state = {
provinceData: [ defaultData],
provinceName: "全部",
cityData: [ defaultData],
cityName: "全部",
districtData: [ defaultData],
districtName: "全部"
}
this. onProvinceChange = this. onProvinceChange. bind( this);
this. onCityChange = this. onCityChange. bind( this);
this. onDistrictChange = this. onDistrictChange. bind( this);
}

componentDidMount() {
getProvinces(). then(( data) => {
this. setState({
provinceData: data
});
}). catch(() => {
this. setState({
provinceData: [ defaultData]
});
});
}

onProvinceChange( pid) {
var pname = "";
this. state. provinceData. forEach(( value) => {
if ( value. ID === pid) {
pname = value. Name;
return false;
}
})
this. setState({
provinceName: pname,
cityName: "全部",
districtName: "全部"
});
if ( pid == 0) {
this. props. callbackParent( pid, 0, 0);
this. setState({
cityData: [ defaultData],
districtData: [ defaultData]
});
} else {
getCities( pid). then(( data) => {
this. setState({
cityData: data
});
}). catch(() => {
this. setState({
cityData: [ defaultData]
});
});
this. props. callbackParent( pid, 0, 0);
}
}

onCityChange( cid) {
var cname = "";
this. state. cityData. forEach(( value) => {
if ( value. ID === cid) {
cname = value. Name;
return false;
}
})
this. setState({
cityName: cname,
districtName: "全部"
});
if( cid == 0){
this. props. callbackParent( this. props. provinceID, cid, 0);
this. setState({
districtData: [ defaultData]
});
} else {
getDistricts( cid). then(( data) => {
this. setState({
districtData: data
});
}). catch(() => {
this. setState({
districtData: [ defaultData]
});
});
this. props. callbackParent( this. props. provinceID, cid, 0);
}
}

onDistrictChange( did) {
var dname = "";
this. state. districtData. forEach(( value) => {
if ( value. ID === did) {
dname = value. Name;
return false;
}
});
this. setState({
districtID: did,
districtName: dname
});
this. props. callbackParent( this. props. provinceID, this. props. cityID, did);
}


render() {
var provinces = this. state. provinceData. map(( item) => {
return < Option key= { item. ID } value= { item. ID } > { item. Name } </ Option >
});
var cities = this. state. cityData. map(( item) => {
return < Option key= { item. ID } value= { item. ID } > { item. Name } </ Option >
});
var districts = this. state. districtData. map(( item) => {
return < Option key= { item. ID } value= { item. ID } > { item. Name } </ Option >
})
return ( < div style= {{ marginBottom: 20 } } >
< Select
style= {{
width: 120,
marginRight: 20
} }
placeholder= "选择省份"
onChange= {this. onProvinceChange }
value= {this. state. provinceName }
>
{ provinces }
</ Select >
< Select
style= {{
width: 120,
marginRight: 20
} }
placeholder= "选择城市"
value= {this. state. cityName }
onChange= {this. onCityChange }
>
{ cities }
</ Select >
< Select
style= {{
width: 120,
marginRight: 20
} }
placeholder= "选择区县"
value= {this. state. districtName }
onChange= {this. onDistrictChange }
>
{ districts }
</ Select >
{this. props. children }
</ div >)
}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React中,父组件向子组件传值可以通过props来实现。父组件可以将需要传递的数据作为属性传递给子组件,子组件通过props来接收这些数据。下面是几种常见的父子组件传值的方式: 1. 父组件通过props传递数据给子组件: 父组件定义一个属性,并将需要传递的数据作为该属性的值,然后将子组件引入到父组件中,并将该属性作为子组件的一个属性传递进去。子组件可以通过props来接收并使用这个数据。例如,父组件中定义属性`txt0`,并将它传递给子组件`Child`: ```javascript <Child txt={this.state.txt0} /> ``` 子组件可以通过props来接收并使用父组件传递的数据: ```javascript this.props.txt ``` 2. 父组件通过回调函数传递数据给子组件: 父组件定义一个回调函数,并将该函数作为属性传递给子组件。子组件可以通过调用这个回调函数,将需要传递的数据作为参数传递给父组件。例如,父组件中定义一个回调函数`getDatas`: ```javascript getDatas(msg){ this.setState({ mess: msg }); } ``` 然后将该函数作为属性传递给子组件`Son`: ```javascript <Son getdata={this.getDatas.bind(this)}></Son> ``` 子组件可以通过调用父组件传递的回调函数,并将需要传递的数据作为参数传递给它: ```javascript this.props.getdata(data); ``` 3. 父组件通过context传递数据给子组件: Context是React提供的一种跨组件传递数据的机制。父组件可以通过定义一个Context,并将需要传递的数据放在Context中,然后子组件可以通过访问Context来获取这些数据。具体的实现可以参考React官方文档中关于Context的介绍。 以上是React父子组件传值的几种常见方式,你可以根据具体的需求选择合适的方式来实现父子组件之间的数据传递。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [React父子组件间的传值的方法](https://download.csdn.net/download/weixin_38595850/13633672)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [React教程:父子组件传值组件通信)](https://blog.csdn.net/p445098355/article/details/104519363)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [React父子组件传值](https://blog.csdn.net/weixin_45817109/article/details/103628428)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值