简体   繁体   English

ReactJS如何从同一文件上的另一个函数调用组件函数?

[英]ReactJS how to call a component function from another function on the same file?

How can i call a component function from function declared on the outside? 如何从外部声明的函数调用组件函数? Here is the code 这是代码

function testFunction(){
    test();
}

class ChatManager extends Component{

    test(){
        console.log("Test");
    }

    render(){

        return(
            <div className="divChatManager" onClick={()=>testFunction()}>

            </div>
        )
    }
}

How can i call a component function from function declared on the outside? 如何从外部声明的函数调用组件函数? Here is the code 这是代码

function testFunction(){
    test();
}

class ChatManager extends Component{

    test(){
        console.log("Test");
    }

    render(){

        return(
            <div className="divChatManager" onClick={()=>testFunction()}>

            </div>
        )
    }
}

EDITED2 EDITED2

Here is what i am trying to achieve, but couldn't get it working because pushToDetail was inside the ChatManager.js 这是我想要实现的,但无法使它工作,因为pushToDetail在ChatManager.js中

Error: Attempted import error: 'pushToDetail' is not exported from './components/ChatManager'. 错误:尝试导入错误:'pushToDetail'未从'./components/ChatManager'导出。

Api.js Api.js

import openSocket from 'socket.io-client';
import axios from 'axios';
import { store } from './components/Store'
import { pushToDetail } from './components/ChatManager'

const socket = openSocket("http://localhost:3000/", 
    {'forceNew': true,
    'reconnection': true,
    'reconnectionDelay': 1000,
    'reconnectionDelayMax': 5000,
    'reconnectionAttempts': 999999,
    });

function connectToChatRoom(receiver_id){
    socket.on(receiver_id, (from_id, message)=>{
        console.log(receiver_id + " has received " + message + " from " + from_id);
        pushToDetail(message) // I want to send the message from here to ChatManager.js
    });
}

ChatManager.js ChatManager.js

import ChatManagerStyle from '../styles/ChatManagerStyle.scss';
import axios from 'axios';
import { store } from './Store'
import ChatItem from './ChatItem';
import ChatDetailItem from './ChatDetailItem';
import { connectToChatRoom, disconnectFromChatRoom, socket } from '../Api';

class ChatManager extends Component{

    state = {
        chatItem: [],
        chatDetail: [],
    }

    constructor(props){
        super(props);
    };

    pushToDetail = (message) => {
        this.setState({ chatDetail:[...this.state.chatDetail, message] });
    }

}

export { ChatManager, pushToDetail }; 

There are at least two ways that I can think of to reach your expected behavior, neither of which I recommend. 我至少有两种方法可以达到预期的行为,我建议不要这样做。 First one by adding test as a static method to the class itself: 首先将test作为静态方法添加到类本身:

function testFunction(){
    ChatManager.test(); // Chatmanager itself is an object
}

class ChatManager extends Component{

    static test(){ // set test as static function
        console.log("Test");
    }
}

Second method by using the bind() method to attribute test() function to an instance: 第二种方法是使用bind()方法将test()函数属性化为一个实例:

function testFunction(){
    this.test(); // call test function on an instance
}

class ChatManager extends Component{

    test(){
        console.log("Test");
    }

    render(){

        return(
            <div className="divChatManager" onClick={ testFunction.bind(this) }>

            </div>
        )
    }
}

Both solutions are very hacky, and as others have mentioned before, the major question you should be asking yourself is why do you want to do this in the first place? 这两种解决方案都很苛刻,正如其他人之前提到的那样,你应该问自己的主要问题是你为什么要这样做呢? Chances are, there is an issue that can be fixed within the conventions of React and not using hacky javascript. 有可能,有一个问题可以在React的约定中修复,而不是使用hacky javascript。

This seems like you're trying to combine 2 concepts. 这似乎是你想要结合2个概念。 A Component is your view logic. Component是您的视图逻辑。 If you need to call a component's method, mark it static but you shouldn't really be mixing view logic with external business logic. 如果需要调用组件的方法,请将其标记为static但不应将视图逻辑与外部业务逻辑混合。 That's what utility folders/files are for or even a reducer/middleware pair. 这就是实用程序文件夹/文件的用途,甚至是reducer / middleware对。

I think what you really want is to define a helper function or factory in a utility file that takes whatever arguments you need to take to produce your output. 我认为你真正想要的是在实用程序文件中定义一个辅助函数或工厂,它接受你需要采取的任何参数来产生输出。

If I'm not wrong, eventually your are trying to setState with message. 如果我没错,最终你会尝试使用消息来设置State。 trigger an action to update state using reducer function. 使用reducer函数触发更新状态的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM