React Native中父组件调用子组件的方法和子组件调用父组件的方法
warning:
这篇文章距离上次修改已过190天,其中的内容可能已经有所变动。
在React Native中,父组件可以通过props传递函数给子组件,子组件可以通过回调函数与父组件通信。以下是实现父组件调用子组件方法和子组件调用父组件方法的示例代码:
// 父组件
import React, { Component } from 'react';
import { View, Text, Button } from 'react-native';
import ChildComponent from './ChildComponent';
export default class ParentComponent extends Component {
parentMethod = () => {
console.log('父组件方法被调用');
};
childMethod = () => {
this.child && this.child.childMethod();
};
render() {
return (
<View>
<Button title="父组件调用子组件方法" onPress={this.childMethod} />
<ChildComponent
ref={(child) => (this.child = child)}
parentMethod={this.parentMethod}
/>
</View>
);
}
}
// 子组件
import React, { Component } from 'react';
import { View, Text, Button } from 'react-native';
export default class ChildComponent extends Component {
childMethod = () => {
console.log('子组件方法被调用');
this.props.parentMethod();
};
render() {
return (
<View>
<Button title="子组件调用父组件方法" onPress={this.childMethod} />
</View>
);
}
}
在这个例子中:
- 父组件通过props向子组件传递一个函数
parentMethod
。 - 子组件通过调用
this.props.parentMethod()
来执行传递进来的函数。 - 父组件使用ref属性来获取子组件的引用,并调用子组件的方法
childMethod
。
这样,父子组件之间就可以通过props和ref进行方法的互相调用。
评论已关闭