- 1.子组件的属性接收一个父组件的方法
2.在子组件中,调用这个方法,向父组件传参
//1.子组件
import React,{Component} from 'react';
class TodoItem extends Component {
constructor(props){
super(props);
this.handleClick = this.handleClick.bind(this)
}
render(){
return (
<div onClick={this.handleClick}>
{this.props.content}
{this.props.index}
</div>
)
}
handleClick(){
this.props.deleteItem(this.props.index)
}
}
export default TodoItem
//2.父组件import React, { Component} from 'react';
import './index.css';
import TodoItem from './components/TodoItem';
class App extends Component {
constructor(props) {
super(props);
this.state ={
list:[1,2,3]
}
}
render() {
return (
<div>
{this.state.list.map((item,index)=>{
return <TodoItem key={index} content={item} index={index}
//向子组件传递一个事件
deleteItem={this.handleDelete.bind(this)}></TodoItem>
})}
</div>
)
}
handleDelete(index){
var list = this.state.list;
list.splice(index,1);
this.setState({
list:list
})
}
}
export default App;