我想在调用socket.on时添加一个类。这样一个小部件就会在特定的socket.id上自动打开。
意图是socket.on('startChat',function(){});添加以便Chat.js文件开始运行。
socket.on('startChat', function() {
});
我的代码:
Website.js
constructor(props) {
super(props);
this.state = {
showComponent: false,
};
socket.on('startChat', function() {
});
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(function(prevState) {
return {
isToggleOn: !prevState.isToggleOn
};
});
}
render() {
return ( <
div >
<
button onClick = {
this.handleClick
} > Test < /button> {
this.state.isToggleOn ?
<
Chat / > :
null
} <
/div>
)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
答案 0 :(得分:0)
您可以使用state.showComponent
有条件地render()
组件。
答案 1 :(得分:0)
convenient将任何处理程序或侦听器附加到componentDidMount()
方法中。{
按照您粘贴的代码:
更新
即使使用ES6 arrow notation,它看起来也不会绑定。确保构造函数存在,并尝试将其绑定回来 添加了反应类和导入。
import React, {Component} from 'react'
class Website extends Component {
constructor(props) {
super(props);
this.state = {
showComponent: false,
isToggleOn: false // I added this
};
// This binding is necessary to make `this` work in the callback
// No if you use the current notation ()=>{}
// this.handleClick = this.handleClick.bind(this);
}
componentDidMount() {
socket.on('startChat', function() {
console.log("Chart started!!!")
});
}
handleClick() {
let state=this.state
state.isToggleOn = !this.state.isToggleOn
this.setState(state);
}
render() {
return (
<div>
<button onClick={this.handleClick().bind(this)}> Test </button>
{ this.state.isToggleOn ? <Chat / > : null }
</div>
)
}
}