首页 > 解决方案 > 我想调用另一个组件的方法

问题描述

我的组件 AddPost.js 使用 machine.js 中存在的机器,在我想调用 AddPost 中存在的方法的最后一个文件中,我尝试导入 AddPost 但它不起作用。我有那个错误:可能未处理的承诺拒绝(id:0):ReferenceError:未定义addInBubble 我想知道如何在machine.js 中调用此方法,因为我在此文件中有操作,我将在行动

AddPost.js

import React, {PureComponent} from 'react';
import {View, Text, TextInput,ScrollView,StyleSheet} from 'react-native';
import {Button,Input,Bubble,ThemeProvider} from 'nachos-ui';
import {Navigation} from 'react-native-navigation';
import PropTypes from 'prop-types';
import {fetchMachine} from '../../helpers/machine.js';

console.disableYellowBox = true;
const styles = StyleSheet.create({
  container :{ 
    marginVertical:15 , flex: 1,
    flexDirection: 'column',
  },
  ButtonView : {
    flex: 1, 
    flexDirection: 'row',
    position: 'absolute',
    bottom:0,

  },
  bubbleStyle:{
     marginBottom: 15,
     marginLeft: 20,
     width: '80%'

    }
});

  let currentState = fetchMachine.initialState;
  let valuesCurrentState = currentState.nextEvents;
class AddPost extends PureComponent {

  static propTypes = {
    componentId: PropTypes.string,
    text:PropTypes.string
  }

  constructor(props) {
    super(props);
    this.state = {
      responseValue :[],
      value1 : 'Yes',
      value2 : 'No',
      value : ''

    };
  }


  addInBubble = () =>{
    let newValue = this.state.value;
    this.setState({      
      responseValue : [...this.state.responseValue,newValue]
    });
  }

  render() {

    let newArray = this.state.responseValue && this.state.responseValue.map(( item, key ) =>{
      return(
        <View key = { key } >
            <Bubble style = { styles.bubbleStyle }> { item }</Bubble>
        </View>
    );
    });
    return (

         <ThemeProvider>
        <View style={styles.container}>
        <ScrollView >
                <View style = {{ flex: 1, padding: 4 }}>
                {
                    newArray
                }
                </View>
        </ScrollView>
          <View style={styles.ButtonView}>
          <Button
              onPress = {this.addInBubble} 
          >
            {this.state.value1}
          </Button>
          <Button
              onPress = {this.addInBubble} 
          >
            {this.state.value2}
          </Button>
          </View>

        </View>
      </ThemeProvider>
    );
  }
}
export default AddPost;

machine.js

import { Machine, actions } from 'xstate';
import {AddPost} from '../screens/Summary/AddPost';

const fetchMachine = Machine({
  id: 'Hands Free',
  context: { attempts: 0},
  initial: 'summary',
  states: {
    summary: {
      on: {
          yes: {
            target: 'prioritization',
            actions: ['activate', 'sendTelemetry']
          },
        no : 'readMails'
      }
    },
    prioritization: {
      on: {
        read: 'readByPrioritization',
        skip: 'readMails'
      }
    },
    readByPrioritization: {

          on: {
        read: 'readMails',
        skip: 'listener'
      }

    },
    readMails: {
      on: {
        next: 'readMails',
        skip: 'listener'
      }
    },
    listener: {

      on: {
        received: 'readSummary',
        notyet: 'listener'
      }
    },
    readSummary: {

      on: {
        read: 'readEmail',
        skip :'listener'
      }
    },
    readEmail: {

      on: {
        finish: 'listener',
      }
    }
  }
},
  {
    actions: {
      // action implementations
      activate: (context, event) => {
        console.log('activating...');
          AddPost.addInBubble(); // this the methode that i want to call
        return 0;
      },
      notifyActive: (context, event) => {
        console.log('active!');
      },
      notifyInactive: (context, event) => {
        console.log('inactive!');
      },
      sendTelemetry: (context, event) => {
        console.log('time:', Date.now());
      }
    }
  });

  export{fetchMachine};

I want to call the method addInBubble but I have an error

标签: javascriptreactjsreact-native

解决方案


您可以将parent方法作为道具传递给child组件以访问它们

Class A extends Component {
  addInBubble = () => {
    // Some logic here
  }

  render() {
    <B addInBubble={this.addInBubble} />
  }

}

所以要在组件 B 中访问

Class B extends Component {

  render() {
    <div onClick={this.props.addInBubble} />
  }

}

推荐阅读