【问题标题】:How to call a child component method from parent in React Native typescript如何在 React Native 打字稿中从父级调用子组件方法
【发布时间】:2019-07-25 13:15:32
【问题描述】:

你好,我是 React Native 中的新手,使用 typescript,在这个示例代码中,我想从父类的 parentCall 函数中的子组件调用 testChild 函数,但我不知道如何保留每个子组件的引用 我无法更改子组件代码 如何为每个子组件调用 testChild?

class parent extends React.Component {
   public render(): JSX.Element {
        return (
         <child/>
         <child/>
               )
 public parentCall(): void{
   //call testChild for each Child component ??
}

}
class child extends React.Component {
 public render(): JSX.Element {
        return (
               <Text>Text</Text>
               )

 public testChild (): string{
   return Data ;
}

【问题讨论】:

    标签: typescript react-native


    【解决方案1】:

    如果我理解正确,您可以将每个 &lt;Child /&gt; 组件存储在一个数组中,例如:const children: JSX.Element[] = [Child, Child]。 render 方法允许您传入用于渲染的组件数组,因此这样做的额外好处是您现在有了一个可以循环并执行 testChild 的变量。

    【讨论】:

      【解决方案2】:

      我通过使用 res 和定义 childRef 字段解决了我的问题 并使用此代码将子组件的 ref 存储在 childRef 中

      private onRef= (ref) =&gt; this.childRef= ref

      并将其设置在子组件中

      <child ref={this.onRef} />
      

      现在有了 childRef 我可以调用它的方法

      childRef.testChild()
      

      【讨论】:

        猜你喜欢
        • 2019-08-10
        • 2016-12-03
        • 1970-01-01
        • 1970-01-01
        • 2018-07-20
        • 2017-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多