Skip to content

Instantly share code, notes, and snippets.

@omas-public
Created December 12, 2019 11:55
Show Gist options
  • Save omas-public/02e3ccb88428cff4aa07bcc1e4c9c4d3 to your computer and use it in GitHub Desktop.
Save omas-public/02e3ccb88428cff4aa07bcc1e4c9c4d3 to your computer and use it in GitHub Desktop.
React Form(p158)
import React from 'react'
import {
TextField,
Button,
FormControl,
makeStyles,
createStyles
} from '@material-ui/core'
const App = props => {
const doSubmit = (event, value) => {
event.preventDefault()
window.alert(JSON.stringify(value))
}
return (
<div>
<MultiForm doSubmit = {doSubmit}/>
<SimpleForm doSubmit = {doSubmit}/>
</div>
)
}
const useStyles = makeStyles((theme: Theme) => createStyles({
form: {
margin:"2em"
},
}))
const SimpleForm = props => {
const classes = useStyles()
const [value, setValue] = React.useState('')
const doChange = event => {
setValue(event.target.value)
}
return (
<FormControl className = {classes.form}>
<TextField
label="入力"
value = {value}
variant="outlined"
size = "small"
onChange = {doChange}
/>
<Button
variant="contained" color="primary"
onClick = {(event) => props.doSubmit(event, value)}
>送信</Button>
</FormControl>
)
}
const MultiForm = props => {
const classes = useStyles()
const [state, setState] = React.useState({
name:'クジラ',
age:22,
hobby:'読書'
})
const doChange = event => {
const value = event.target.value
const key = event.target.name
setState({[key]:value})
}
return (
<FormControl className = {classes.form}>
<TextField
label="名前"
name = 'name'
value = {state.name}
variant="outlined"
size = "small"
onChange = {doChange} />
<TextField
label="年齢"
name = 'age'
value = {state.age}
variant="outlined"
size = "small"
onChange = {doChange} />
<TextField
label="趣味"
name = 'hobby'
value = {state.hobby}
variant="outlined"
size = "small"
onChange = {doChange} />
<Button
variant="contained" color="primary"
onClick = {(event) => props.doSubmit(event, state)}>
送信
</Button>
</FormControl>
)
}
export default App
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment