在react-native

时间:2017-05-13 13:37:23

标签: javascript react-native react-native-android

如何在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..');
    }

    ....
}

3 个答案:

答案 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)

在功能组件中调用远程方法

要对功能组件执行此操作,您必须这样做:

父母

  1. 使用 useRef() 在父组件中为子组件提供一个引用:
const childRef = useRef()
// ...
return (
   <ChildComponent ref={childRef} />
)
...

儿童

  1. ref 传入构造函数:
const ChildComponent = (props, ref) => {
  // ...
}
  1. useImperativeHandle 导入 forwardRef'react'
import React, { useImperativeHandle, forwardRef } from 'react'
  1. 使用 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")
  }
  // ..
}
  1. 使用 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();