如何在react-native中调用其他组件的函数?
我有这个自定义组件,它可以在其他地方呈现另一个组件和一个图像按钮。当点击图像时,我想从另一个组件调用一个函数。执行下面的示例时,我得到undefined is not an object (evaluating this.otherComponent.doSomething')
export default class MainComponent extends Component {
_onPressButton() {
this.otherComponent.doSomething();
}
render() {
return (
<View style={styles.container}>
<TagContainer style={styles.flow_container} ref={(instance) => this.otherComponent = instance}>
</TagContainer>
<TouchableHighlight onPress={this._onPressButton}><Image source={require('./img/ic_add.png')} style={styles.add_tags_button_view} /></TouchableHighlight>
</View>
);
}
}
和
export default class OtherComponent extends Component {
addTag() {
this.state.tags = this.state.tags.push("plm");
console.log('success..');
}
....
}
答案 0 :(得分:6)
不推荐组件之间的直接通信,因为它会破坏封装。向组件发送道具并让它处理方法/wp-content/uploads
内的更改是一种很好的做法。
componentWillReceiveProps
class Main extends React.Component {
constructor(props) {
super(props);
this.state = { value: 0 };
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
e.preventDefault();
this.setState({ value: ++this.state.value });
}
render() {
return (
<div>
<a href="#" onClick={this.handleClick}>click me</a>
<Child value={this.state.value}/>
</div>
);
}
}
class Child extends React.Component {
constructor(props) {
super(props);
this.state = { value: 0 };
}
componentWillReceiveProps(nextProps) {
if(nextProps.value !== this.state.value) {
this.setState({ value: nextProps.value });
}
}
render() {
return <div>{this.state.value}</div>
}
}
ReactDOM.render(<Main />, document.getElementById('app'));
答案 1 :(得分:0)
要对功能组件执行此操作,您必须这样做:
父母
useRef()
在父组件中为子组件提供一个引用:const childRef = useRef()
// ...
return (
<ChildComponent ref={childRef} />
)
...
儿童
ref
传入构造函数:const ChildComponent = (props, ref) => {
// ...
}
useImperativeHandle
导入 forwardRef
和 'react'
:import React, { useImperativeHandle, forwardRef } from 'react'
useImperativeHandle
将方法连接到 ref
对象。这些方法在内部不可用,因此您可能需要使用它们来调用内部方法。
const ChildComponent = (props, ref) => {
//...
useImperativeHandle(ref, () => ({
// each key is connected to `ref` as a method name
// they can execute code directly, or call a local method
method1: () => { localMethod1() },
method2: () => { console.log("Remote method 2 executed") }
}))
//...
// These are local methods, they are not seen by `ref`,
const localMethod1 = () => {
console.log("Method 1 executed")
}
// ..
}
forwardRef
导出子组件:const ChildComponent = (props, ref) => {
// ...
}
export default forwardRef(ChildComponent)
子组件
import React, { useImperativeHandle, forwardRef } from 'react';
import { View } from 'react-native'
const ChildComponent = (props, ref) => {
useImperativeHandle(ref, () => ({
// methods connected to `ref`
sayHi: () => { sayHi() }
}))
// internal method
const sayHi = () => {
console.log("Hello")
}
return (
<View />
);
}
export default forwardRef(ChildComponent)
父组件
import React, { useRef } from 'react';
import { Button, View } from 'react-native';
import ChildComponent from './components/ChildComponent';
const App = () => {
const childRef = useRef()
return (
<View>
<ChildComponent ref={childRef} />
<Button
onPress={() => {
childRef.current.sayHi()
}}
title="Execute Child Method"
/>
</View>
)
}
export default App
Expo Snacks 上有一个互动演示: https://snack.expo.dev/@backupbrain/calling-functions-from-other-components
这个解释是从这个TutorialsPoint article
答案 2 :(得分:-3)
无需在类中定义函数。这是一个例子
在helpers.js
中export async function getAccessKey(){
let accessToken = await AsyncStorage.getItem(ACCESS_TOKEN);
return accessToken;
}
在通话类中。
import { getAccessKey } from '../components/helpers';
...
//inside the method
let key = await getAccessKey();