Created
December 12, 2019 11:55
-
-
Save omas-public/02e3ccb88428cff4aa07bcc1e4c9c4d3 to your computer and use it in GitHub Desktop.
React Form(p158)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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