简体   繁体   中英

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

Here is what i am trying to achieve, but couldn't get it working because pushToDetail was inside the ChatManager.js

Error: Attempted import error: 'pushToDetail' is not exported from './components/ChatManager'.

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

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:

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:

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.

This seems like you're trying to combine 2 concepts. A Component is your view logic. 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. That's what utility folders/files are for or even a reducer/middleware pair.

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. trigger an action to update state using reducer function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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