在我的react组件中,我使用react-apollo从graphQL服务器获取一些数据。 这个工作正常,但是这个组件是子组件,我需要将graphQL数据提供给父组件。这是可能的还是我必须改变我的结构?
儿童
export class Child extends Component {
const { contentList } = this.props
render () {
contentList.map(elm => return <div>elm</div>)
}
}
export default compose(
graphql(
gql`
query {
contentList {
_id
title
}
}
`, { name: 'contentList' }
)
)(Child)
父
export class Parent extends Component {
constructor () {
super()
this.state = {
data = null // <-- Need to get the data of child here
}
}
render () {
const { data } = this.state
// Now I can use the data, which is fetched by the child component
return <Child />
}
}
答案 0 :(得分:-1)
您可以通过props将parent的函数传递给childComponent,并在有数据时从子函数调用该函数。
export class Parent extends Component {
constructor () {
super();
this.handleData = this.handleData.bind(this);
this.state = {
data = null // <-- Need to get the data of child here
}
}
handleData(data){
//you can use data here
}
render () {
const { data } = this.state
// Now I can use the data, which is fetched by the child component
return <Child parentHandler="this.handleData" />
}
}
export class Child extends Component {
const { contentList, parentHandler } = this.props;
//call parentHandler with the data when you have data
render () {
contentList.map(elm => return <div>elm</div>)
}
}
export default compose(
graphql(
gql`
query {
contentList {
_id
title
}
}
`, { name: 'contentList' }
)
)(Child)