Answer the question
In order to leave comments, you need to log in
How to correctly pass data between components?
Good afternoon. I'm going through the tutorial right now and I have a question. There is some object with myNews news, the App component has a state with these news, and we pass a function to the Add component in a prop that has access to the news. The new news item is added to the myNews object, but it is empty.
App Component:
class App extends React.Component {
state = {
news: myNews
};
handleAddNews(newPost) { //1
const nextNews = [newPost, ...this.state.news];
this.setState({news: nextNews});
};
render() {
return (
<React.Fragment>
<Add newsadd={this.handleAddNews.bind(this, arguments)}/>
<h3>Новости</h3>
<News newsdata={this.state.news} />
</React.Fragment>
)
}
};
class Add extends React.Component {
state = {
namestate: '',
textstate: '',
checkstate: false
};
hundleBtnMessage(e) { //2
e.preventDefault();
const {namestate, textstate} = this.state;
this.props.newsadd({namestate, textstate});
};
handleCheckboxChange(e) {
return this.setState({checkstate: e.currentTarget.checked});
};
handleChange(e) {
const {id, value} = e.currentTarget;
return this.setState({[id]: e.currentTarget.value});
};
handleChangeText(e) {
return this.setState({textstate: e.currentTarget.value});
};
validate() {
const { namestate, textstate, checkstate } = this.state;
if (namestate.trim() && textstate.trim() && checkstate) {
return true;
}
return false;
}
render() {
const { namestate, textstate, checkstate } = this.state;
return (
<form className='add'>
<input
id='namestate'
type='text'
className='add__author'
placeholder='Ваше имя'
onChange={this.handleChange.bind(this)}
value={namestate}
/>
<textarea
id='textstate'
className='add__text'
placeholder='Текст новости'
onChange={this.handleChange.bind(this)}
value={textstate}
></textarea>
<label className='add__checkrule'>
<input type='checkbox'
onChange={this.handleCheckboxChange.bind(this)}/>
Я согласен с правилами
</label>
<button
className='add__btn'
onClick={this.hundleBtnMessage.bind(this)}
disabled={!this.validate.call(this)}>
Показать alert
</button>
</form>
)
}
};
Add.propTypes = {
newsadd: PropTypes.func.isRequired,
}
};
Answer the question
In order to leave comments, you need to log in
this.handleAddNews.bind(this, arguments)
<Add newsadd={this.handleAddNews} />
https://jsfiddle.net/ybeaz/njLx57u4/
here is a simple working example, hope you understand
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question