如何在React Native中使用道具使用从父级父级组件到子级组件的方法?

时间:2020-03-04 12:34:09

标签: reactjs react-native react-hooks

const GrandParent = (props) => {
  const close = () => {
    console.log("Pressed");
  }
  return (<Parent func={() => close()} />)
}

const Parent = (props) => {
  return (<Child onPress={ /**call close function from GrandParent component*/} />)
}

const Child = (props) => {
  return (<Button onPress={() => props.onPress} />)
}

我可以使用GrandParentParent组件中调用props的组件方法,但是我想从Child组件中调用它,但是我不能似乎做到了。

2 个答案:

答案 0 :(得分:1)

它应该像这样工作:

const GrandParent = (props) => {
  const close = () => {
    console.log("Pressed")
  }
  return (<Parent func={() => close()} />)
}

const Parent = (props) => {
  return (<Child func={() => props.func()} />)
}

const Child = (props) => {
  return (<Button onPress={() => props.func()} />)
}

答案 1 :(得分:1)

const GrandParent = (props) => {
  const close = () => {
    console.log("Pressed");
  }
 return (<Parent func={() => close()} />)
}

const Parent = (props) => {
  return (<Child onPress={()=> props.func()} fun1={()=> props.func()}/>)
}

const Child = (props) => {
  return (<Button onPress={()=> props.func1()} />)
}