[英]How to change constants and useEffect in reactjs from a function to a render component
I have this code in a function我在 function 中有这个代码
function Lobby () {
but I wanted to pass it on to class Lobby extends Component {
for a component with但我想将它传递给
class Lobby extends Component {
用于具有
render () {
return (
but putting these const and useEffect ect.. gives me an error, is there any way to "translate" this into a component?但是把这些 const 和 useEffect 等..给我一个错误,有没有办法将它“翻译”成一个组件?
I thank those who can help me我感谢那些可以帮助我的人
original code:原始代码:
function Lobby () {
const [message, updateMessage] = useState('')
const [messages, updateMessages] = useState([])
useEffect(() => {
const handleNewMessage = newMessage =>
updateMessages([...messages, newMessage])
socket.on('chat.message', handleNewMessage)
return () => socket.off('chat.message', handleNewMessage)
}, [messages])
const handleFormSubmit = event => {
event.preventDefault()
if (message.trim()) {
socket.emit('chat.message', {
userid: myId,
lobby,
username: username,
message
})
updateMessage('')
const recibesound = document.getElementsByClassName("audio-element")[0]
recibesound.play()
}
}
const handleInputChange = event =>
updateMessage(event.target.value)
////teste
const handleTesteChange = event =>
updateMessage(event.target.value)
const handleTesteSubmit = event => {
event.preventDefault()
if (message.trim()) {
socket.emit('chat.message', {
userid: myId,
message
})
updateMessage('')
}
}
///teste
return( <div>
//html
</div>
)}
export default Lobby;
goal:目标:
class Lobby extends Component {
// same code
render() {
return(
<div>
//html
</div>
);
}
}
From understanding you are attempting to convert your hooks function component to a class component.根据您的理解,您正在尝试将您的钩子 function 组件转换为 class 组件。 You cannot use any of your hooks functions in a class component.
您不能在 class 组件中使用任何挂钩函数。 You have to rewrite your class component using
this.setState()
instead of the useState hook (instead of updateMessage, and updateMessages) and this.state.message
instead of 'message', and using the componentDidUpdate
method instead of the useEffect hook.您必须使用
this.setState()
而不是 useState 钩子(而不是 updateMessage 和 updateMessages)和this.state.message
而不是“消息”,并使用componentDidUpdate
方法而不是 useEffect 钩子来重写您的 class 组件。 For your functions (handleInputChange), you can define them as method for your class.对于您的函数 (handleInputChange),您可以将它们定义为 class 的方法。 For your constant (recibesound), you can define it outside your class.
对于您的常量(recibesound),您可以在 class 之外定义它。
In short, you have to rewrite your component.简而言之,你必须重写你的组件。 I recommend viewing a React tutorial on class components.
我建议查看有关 class 组件的 React 教程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.