• 1.子组件的属性接收一个父组件的方法
    • 2.在子组件中,调用这个方法,向父组件传参

      1. //1.子组件
      2. import React,{Component} from 'react';
      3. class TodoItem extends Component {
      4. constructor(props){
      5. super(props);
      6. this.handleClick = this.handleClick.bind(this)
      7. }
      8. render(){
      9. return (
      10. <div onClick={this.handleClick}>
      11. {this.props.content}
      12. {this.props.index}
      13. </div>
      14. )
      15. }
      16. handleClick(){
      17. this.props.deleteItem(this.props.index)
      18. }
      19. }
      20. export default TodoItem
      1. //2.父组件import React, { Component} from 'react';
      2. import './index.css';
      3. import TodoItem from './components/TodoItem';
      4. class App extends Component {
      5. constructor(props) {
      6. super(props);
      7. this.state ={
      8. list:[1,2,3]
      9. }
      10. }
      11. render() {
      12. return (
      13. <div>
      14. {this.state.list.map((item,index)=>{
      15. return <TodoItem key={index} content={item} index={index}
      16. //向子组件传递一个事件
      17. deleteItem={this.handleDelete.bind(this)}></TodoItem>
      18. })}
      19. </div>
      20. )
      21. }
      22. handleDelete(index){
      23. var list = this.state.list;
      24. list.splice(index,1);
      25. this.setState({
      26. list:list
      27. })
      28. }
      29. }
      30. export default App;