Created
July 2, 2020 08:20
-
-
Save amorkovin/546f04d8049ba5ac6ee4f3b430fff4c7 to your computer and use it in GitHub Desktop.
Реакт: отправка полей формы
This file contains 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
const wordsList = [ | |
{ | |
eng: 'between', | |
rus: 'между', | |
id: 1 | |
}, | |
{ | |
eng: 'high', | |
rus: 'высокий', | |
id: 2 | |
}, | |
]; | |
class App extends React.Component { | |
state = { | |
wordArr: wordsList, | |
enNewValueCard: false, | |
rusNewValueCard: false | |
} | |
// При вводе в поля меняю state компонента, сохраняя туда введенное значение | |
handleChangeEnValueCard = (e) => { | |
this.setState({ | |
enNewValueCard: e.target.value, | |
}); | |
} | |
handleChangeRusValueCard = (e) => { | |
this.setState({ | |
rusNewValueCard: e.target.value, | |
}); | |
} | |
// Отправка формы добавления новой карточки | |
handleAddNewCard = (e) => { | |
e.preventDefault(); | |
// Поскольку есть зависимость от старого значения state.wordArr я использую здесь стрелочную функцию | |
this.setState((state) => { | |
const changed_word_arr = state.wordArr; | |
const last_id = changed_word_arr[changed_word_arr.length - 1].id; | |
changed_word_arr.push({ | |
eng: this.state.enNewValueCard, | |
rus: this.state.rusNewValueCard, | |
id: last_id + 1 | |
}); | |
return { | |
wordArr: changed_word_arr | |
} | |
}); | |
} | |
render() { | |
const {wordArr} = this.state; | |
return ( | |
<> | |
<form onSubmit={this.handleAddNewCard} className="add-new-card-form"> | |
<input type="text" placeholder="Англ." className="add-new-card-form__en" | |
onChange={this.handleChangeEnValueCard}/> | |
<input type="text" placeholder="Рус." className="add-new-card-form__rus" | |
onChange={this.handleChangeRusValueCard}/> | |
<button type="submit">Добавить</button> | |
</form> | |
<CardList onDeletedItem={(id) => console.log('####: 3 level, id = ', id)} item={wordArr}/> | |
</> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment