zoukankan      html  css  js  c++  java
  • React笔记04——组件拆分与传值

    对组件进行适当的拆分有利于项目维护。

    例子:结合上一节TodoList的项目,将list中的每一项都拆分成一个组件

    新建一个组件文件(即list中的某一项)TodoItem.js

    实现添加功能

    content :父组件通过属性的方式向子组件传值(告诉子组件我们要传递的内容)

    this.props :子组件接收父组件传递的值

    //TodoItem.js
    import React,{ Component } from 'react';
    
    class TodoItem extends Component{
    	render() {
    		// const content = this.props.content;
    		const { content } = this.props;//es6写法,与上面等价
    		return <li>{content}</li>
    	}
    }
    
    export default TodoItem;
    //TodoList.js
    //1、引入子组件
    import TodoItem from './TodoItem';
    //2、修改getListItems函数中的代码 
    getListItems() { return this.state.list.map((value,index) => { return (<TodoItem content = {value} key = {index}/>); }) }

    实现删除功能

    需求:点击list中的某一项,将其删除。

    相当于在子组件中修改父组件中的数据。

    父组件除了可以给子组件传值还可以给子组件传方法。

    为TodoItem中的li标签绑定onClick事件。

    TodoList.js:32 Uncaught TypeError: Cannot read property 'list' of undefined

    报错的原因还是this指向不对,此时this指向TodoItem,在constructor中将this强制指向TodoList即可。

    //TodoItem.js
    import React,{ Component } from 'react';
    
    class TodoItem extends Component{
    	constructor(props) {
    		super(props);
    		this.handleItemClick = this.handleItemClick.bind(this);
    	}
    	handleItemClick() {
    		//改变父组件中list的数据
    		// console.log(this);//TodoItem
    		// this.props.deleteFunction(this.props.index);
    		const { deleteFunction,index } = this.props;//es6解构赋值
    		deleteFunction(index);
    	}
    	render() {
    		// const content = this.props.content;
    		const { content } = this.props;//es6写法,与上面等价
    		return <li onClick = {this.handleItemClick}>{content}</li>
    	}
    }
    
    export default TodoItem;
    //TodoList.js
    
    //在constructor中添加handleItemClick函数的this指向
    this.handleItemClick = this.handleItemClick.bind(this);
    
    //修改getListItems函数
    	getListItems() {
    		return this.state.list.map((value,index) => {
        		return (<TodoItem content = {value} index = {index} key = {index} deleteFunction = {this.handleItemClick}/>);
        		})
    		}

    组件树⬇️:

  • 相关阅读:
    GCD HDU
    Finding Lines UVALive
    Chinese Mahjong UVA
    DNA Evolution CodeForces
    String Reconstruction (并查集)
    Number Cutting Game HDU
    Paint the Wall ZOJ
    Star sky CodeForces
    Haunted Graveyard ZOJ
    GuGuFishtion HDU
  • 原文地址:https://www.cnblogs.com/superjishere/p/12100526.html
Copyright © 2011-2022 走看看