[英]How to call a child component method from parent in React Native typescript
hello i'm new in React Native with typescript and in this example code i want to call testChild function from child Component in parentCall function in parent class and i dont know how to keep reference of each child component i cant change child component code how can i call testChild for each child component ? 你好,我是React Native的新打字员,在此示例代码中,我想从父类的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 ;
}
If I understand you correctly, you can store each <Child />
component in an array like: const children: JSX.Element[] = [Child, Child]
. 如果我对您的理解正确,则可以将每个<Child />
组件存储在以下数组中: const children: JSX.Element[] = [Child, Child]
。 The render method allows you to pass in arrays of components for rendering, so the added bonus of this is you now have a variable you can loop over and execute testChild
with. render方法允许您传入要渲染的组件数组,因此,它的另一个好处是您现在有了一个可以循环使用并执行testChild
的变量。
i solve my problem with Using res and define childRef field and with this code i store ref of child component in childRef 我解决了使用res和定义childRef字段的问题,并使用此代码将子组件的ref存储在childRef中
private onRef= (ref) => this.childRef= ref
and set it in child component 并将其设置在子组件中
<child ref={this.onRef} />
now with childRef i can call its methods 现在使用childRef我可以调用其方法
childRef.testChild()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.