Convert to functional component

This commit is contained in:
Franck Royer 2021-04-22 17:01:46 +10:00
parent c7ba19f43e
commit 5aee9f4841
No known key found for this signature in database
GPG Key ID: A82ED75A8DFC50A4
1 changed files with 16 additions and 28 deletions

View File

@ -1,4 +1,4 @@
import React, { ChangeEvent, KeyboardEvent } from 'react';
import React, { ChangeEvent, KeyboardEvent, useState } from 'react';
import { Button, Grid, TextField } from '@material-ui/core';
interface Props {
@ -6,58 +6,46 @@ interface Props {
sendMessage: () => void;
}
interface State {
inputText: string;
}
export default function MessageInput(props: Props) {
const [inputText, setInputText] = useState<string>('')
export default class MessageInput extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
inputText: ''
};
const sendMessage = () => {
props.sendMessage()
setInputText('')
}
messageHandler(event: ChangeEvent<HTMLInputElement>) {
this.setState({inputText: event.target.value})
this.props.messageHandler(event.target.value);
}
const messageHandler = (event: ChangeEvent<HTMLInputElement>) => {
setInputText(event.target.value)
props.messageHandler(event.target.value);
};
keyPressHandler(event: KeyboardEvent<HTMLInputElement>) {
const keyPressHandler = (event: KeyboardEvent<HTMLInputElement>) => {
if (event.key === 'Enter') {
this.sendMessage()
sendMessage()
}
}
sendMessage() {
this.props.sendMessage()
this.setState({inputText: ''})
}
render() {
return (
<Grid container spacing={2} direction='row' alignItems='center'>
<Grid item xs={11}>
<TextField variant='outlined'
label='Send a message'
value={this.state.inputText}
value={inputText}
fullWidth
style={{ margin: 8 }}
margin="normal"
InputLabelProps={{
shrink: true,
}}
onChange={this.messageHandler.bind(this)}
onKeyPress={this.keyPressHandler.bind(this)}
onChange={messageHandler}
onKeyPress={keyPressHandler}
/>
</Grid>
<Grid item xs={1}>
<Button variant="contained" color="primary" size="large" onClick={this.sendMessage.bind(this)}>
<Button variant="contained" color="primary" size="large" onClick={sendMessage}>
Send
</Button>
</Grid>
</Grid>
);
}
}