Witam,
Mam pytanie odnośnie sensu używania komponentów w bibliotece React. Otóż Mam dylemat odnośnie dwóch programów, które działają identycznie z punktu widzenia użytkownika, natomiast czy drugi program napisany z użyciem komponentów PositiveMessage oraz NegativeMessage jest pod jakimś względem lepszy od pierwszego programu ? Jeśli tak to proszę o wyjaśnienie.
class App extends React.Component {
state = {
check: false,
isFormSubmitted: false
}
handleChangeChecked = () => {
this.setState({
check: !this.state.check,
isFormSubmitted: false
})
return (true)
}
displayMsg = () => {
if (this.state.isFormSubmitted == true) {
if (this.state.check == true)
return (<p>Możesz obejrzeć film!</p>)
else return (<p>Nie możesz obejrzeć filmu.</p>)
} else return (null)
}
handleFormSubmit = (e) => {
e.preventDefault()
this.setState({
isFormSubmitted: true
})
}
render() {
return (
<React.Fragment>
<h1>Kup bilet</h1>
<form onSubmit={this.handleFormSubmit}>
<input type="checkbox" onChange={this.handleChangeChecked} checked={this.state.check} />
<label>Mam conajmniej 16 lat</label>
<button>Kup bilet</button>
</form>
{this.displayMsg()}
</React.Fragment>
)
}
}
ReactDOM.render(< App />, document.getElementById('root'));
const PositiveMessage = () => <p>Mozesz obejrzeć film, zapraszam</p>;
const NegativeMessage = () => <p>Nie możesz obejrzeć tego filmu !</p>;
class TicketShop extends React.Component {
state = {
isConfirmed: false,
isFormSubmitted: false
}
handleCheckboxChange = () => {
this.setState({
isConfirmed: !this.state.isConfirmed,
isFormSubmitted: false
})
}
displayMessage = () => {
if (this.state.isFormSubmitted) {
if (this.state.isConfirmed) { return <PositiveMessage /> }
else { return <NegativeMessage /> }
} else { return null }
}
handleFormSubmit = (e) => {
e.preventDefault()
if (!this.state.isFormSubmitted) {
this.setState({
isFormSubmitted: !this.state.isFormSubmitted
})
}
}
render() {
return (
<>
<h1>Kup bilet na horror roku !</h1>
<form onSubmit={this.handleFormSubmit}>
<input type="checkbox" id="age" onChange={this.handleCheckboxChange} checked={this.state.isConfirmed} />
<label htmlFor="age">Mam conajmniej 16 lat</label>
<br />
<button type="submit">Kup bilet</button>
</form>
{this.displayMessage()}
</>
)
}
}
ReactDOM.render(<TicketShop />, document.getElementById('root'))