javascript - 我想调用另一个组件的方法

标签 javascript reactjs react-native

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

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;

机器.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

最佳答案

您可以将parent方法作为 Prop 传递给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} />
  }

}

关于javascript - 我想调用另一个组件的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55793019/

相关文章:

javascript - 修复了 anchor 到错误位置的菜单

javascript - 使用 typescript 安装express.js 的正确方法是什么?

javascript - jQuery hasClass 不起作用或 if 语句有缺陷

javascript - React 中设置的时间选择器 - jquery-timepicker

android - 没有 Android Studio 的 React Native?

javascript - 为什么这个 JavaScript 不起作用?

reactjs - MUI 在 <Input> 组件的焦点上更改条形颜色

javascript - 如何使用 setInterval 或其他方式在 React 中重新渲染特定组件?

javascript - 用户签到位置基于从哪里开始?

ios - React-Native ios 应用程序在我的手机上崩溃