假设父组件是一个收货地址信息,子组件是区域信息,子组件的默认值由父组件传入,并且子组件选择区域后,父组件中的收货地址的区域信息要跟着修改,需要在向子组件传入区域信息的时候,也要传入区域信息改变事件
父组件:
import React from 'react';
import StateInfo from "./stateInfo";
class AddressInfo extends React.Component {
constructor(props) {
super(props);
this.state = {
"id": 46,
"code": "NY",
"name": "New York"
}
this.stateRef = React.createRef()
}
handleChangeState = (state => {
this.setState(state )
})
render() {
return (
<StateInfo
ref={this.stateRef}
name={this.state.state.name}
handleChangeState={this.handleChangeState}/>
);
}
}
export default AddressInfo;
子组件:
import React from 'react';
class StateInfo extends React.Component {
constructor(props) {
super(props);
this.state = {
list: []
}
}
handleGetstates = (countryId) => {
request(url).then(body => {
const list = JSON.parse(body)
this.setState({ list })
console.log(list)
if (list.length > 0)
this.props.handleChangeState(list[0])
else
this.props.handleChangeState({state: '', id: 0, code: ''})
}).catch(err => {
console.log(err)
})
}
render() {
return (
<div className="dropdown">
{
this.state.list.map(state => (
<a
key={state.id}
className="dropdown-item"
href="#"
onClick={() => {this.props.handleChangeState(state)}}>
{state.name}
</a>
))
}
</div>
);
}
}
export default StateInfo;