[英]ReactJS how to call a component function from another function on the same file?
如何从外部声明的函数调用组件函数? 这是代码
function testFunction(){
test();
}
class ChatManager extends Component{
test(){
console.log("Test");
}
render(){
return(
<div className="divChatManager" onClick={()=>testFunction()}>
</div>
)
}
}
如何从外部声明的函数调用组件函数? 这是代码
function testFunction(){
test();
}
class ChatManager extends Component{
test(){
console.log("Test");
}
render(){
return(
<div className="divChatManager" onClick={()=>testFunction()}>
</div>
)
}
}
EDITED2
这是我想要实现的,但无法使它工作,因为pushToDetail在ChatManager.js中
错误:尝试导入错误:'pushToDetail'未从'./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 };
我至少有两种方法可以达到预期的行为,我建议不要这样做。 首先将test作为静态方法添加到类本身:
function testFunction(){
ChatManager.test(); // Chatmanager itself is an object
}
class ChatManager extends Component{
static test(){ // set test as static function
console.log("Test");
}
}
第二种方法是使用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>
)
}
}
这两种解决方案都很苛刻,正如其他人之前提到的那样,你应该问自己的主要问题是你为什么要这样做呢? 有可能,有一个问题可以在React的约定中修复,而不是使用hacky javascript。
这似乎是你想要结合2个概念。 Component
是您的视图逻辑。 如果需要调用组件的方法,请将其标记为static
但不应将视图逻辑与外部业务逻辑混合。 这就是实用程序文件夹/文件的用途,甚至是reducer / middleware对。
我认为你真正想要的是在实用程序文件中定义一个辅助函数或工厂,它接受你需要采取的任何参数来产生输出。
如果我没错,最终你会尝试使用消息来设置State。 使用reducer函数触发更新状态的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.