Javascript 子组件获取数据,这些数据应该传递给父组件
在我的react组件中,我确实使用react apollo从graphQL服务器获取了一些数据。 这很好,但是这个组件是一个子组件,我需要将graphQL数据获取到父组件。这是可能的还是我必须改变我的结构 儿童Javascript 子组件获取数据,这些数据应该传递给父组件,javascript,reactjs,graphql,Javascript,Reactjs,Graphql,在我的react组件中,我确实使用react apollo从graphQL服务器获取了一些数据。 这很好,但是这个组件是一个子组件,我需要将graphQL数据获取到父组件。这是可能的还是我必须改变我的结构 儿童 export class Child extends Component { const { contentList } = this.props render () { contentList.map(elm => return <div>elm<
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)
导出类子扩展组件{
const{contentList}=this.props
渲染(){
map(elm=>returnelm)
}
}
导出默认组合(
图形ql(
gql`
质疑{
内容列表{
_身份证
标题
}
}
`,{name:'contentList'}
)
)(儿童)
家长
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 />
}
}
导出类父级扩展组件{
构造函数(){
超级()
此.state={
data=null/您可以通过props将parent函数传递给childComponent,并在有数据时从child调用该函数
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)
导出类父级扩展组件{
构造函数(){
超级();
this.handleData=this.handleData.bind(this);
此.state={
数据=null//返回elm)
}
}
导出默认组合(
图形ql(
gql`
质疑{
内容列表{
_身份证
标题
}
}
`,{name:'contentList'}
)
)(儿童)
您可以将父对象的函数作为道具传递给子对象,然后从子对象调用它,传递数据。另外:@ChrisG但是子对象的调用应该是什么样子的?数据是通过compose附加到子组件的……如果我使用函数,我知道该如何做,比如单击一个按钮或子组件。But在本例中,graphql数据让我感到困惑…查看父级的render()
function,看起来您想在创建子组件之前访问子组件的数据…?我认为这行不通。@ChrisG我想先渲染父组件,然后渲染子组件,它获取数据,然后将数据传递回父组件状态,现在用传递的数据重新渲染父组件…不要更改render()中的状态
,因为这将导致一个无限循环。只需将数据提取移到父级,整个问题就会烟消云散。