class TasksList extends React.Component {
addItem(event){
event.preventDefault();
console.log(event.refs.itemInput.value);
let input = event.refs.itemInput.value;
this.props.onAddItem(input);
}
render(){
return(
<div className="col-sm-5 col-xs-12">
<h2> Items </h2>
<form className="form-inline" onSubmit={this.addItem.bind(this)}>
<input type="text" ref="itemInput" placeholder="Type name here..." className="form-control" />
<input type="submit" ref='itemSubmit' value="Add new" className="btn btn-info" />
</form >
</div>
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
tasks: [{
active: true,
content: "Eat chicken",
comments: ["comment1", "comment2"]
}
]
};
}
onAddItem(content){
this.setState({
tasks: this.state.tasks.concat.push(content: content, comments: [], active: true)
});
}
render(){
return(
<div className="container-fluid" >
<div className="row app-row">
<LogoBar />
<TasksList tasks = {this.state.tasks} addItem={this.onAddItem.bind(this)} />
</div>
</div>
)
}
}
main.js:66615 Uncaught TypeError: Cannot read property 'itemInput' of undefined
at TasksList.addItem (main.js:66615)
at HTMLUnknownElement.boundFunc
this.setState(prevState => ({
tasks: [
...prevState.tasks,
{ content, comments: [], active: true},
],
}));
constructor(props) {
super(props);
this.onAddItem = this.onAddItem.bind(this);
}
onAddItem = content => {
// some stuff
};
class Example extends Component {
state = {
inputValue: '',
};
handleChange = e => {
const { name, value } = e.target;
this.setState({
[name]: value,
});
};
render() {
const { inputValue } = this.state;
return (
<Wrapper>
<input
name="inputValue"
value={inputValue}
onChange={this.handleChange}
/>
...
</Wrapper>
);
}
Код родителя:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
tasks: [{
active: true,
content: "Eat chicken",
comments: ["comment1", "comment2"]
}
]
};
}
needData(data){
console.log("data",data)
}
onAddItem(content){
this.setState({
tasks: this.state.tasks.concat.push(content: content, comments: [], active: true)
});
}
render(){
return(
<div className="container-fluid" >
<div className="row app-row">
<LogoBar />
<TasksList tasks = {this.state.tasks} addItem={this.onAddItem.bind(this)} needData={()=>this.needData}/>
</div>
</div>
)
}
}
Код ребенка:
class TasksList extends React.Component {
addItem(event){
event.preventDefault();
console.log(event.refs.itemInput.value);
let input = event.refs.itemInput.value;
this.props.onAddItem(input);
this.props.needData(input)
}
render(){
return(
<div className="col-sm-5 col-xs-12">
<h2> Items </h2>
<form className="form-inline" onSubmit={this.addItem.bind(this)}>
<input type="text" ref="itemInput" placeholder="Type name here..." className="form-control" />
<input type="submit" ref='itemSubmit' value="Add new" className="btn btn-info" />
</form >
</div>