React组件拆分与传值

组件拆分与组件之间的传值

父子组件的概念:

父组件通过属性的方式,向自组件传值

子组件通过this.props的属性,接收传递过来的值

父组件

src/TodoList.js

import React,{Component,Fragment} from 'react';
import TodoItem from './TodoItem';
import './style.css';

class TodoList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            inputVal:'',
            list:[] 
        };

        this.changeVal=this.changeVal.bind(this);
        this.addItem=this.addItem.bind(this);
        this.deleteItem=this.deleteItem.bind(this);
    }

    changeVal(e){
        this.setState({
            inputVal: e.target.value
        });
    }

    addItem(e){
        //按下回车键
        if(e.keyCode===13 && e.target.value!==""){
            const list=[...this.state.list,e.target.value]

            this.setState({
                //list:list
                //对象的键值相同时,简写
                list,
                inputVal:''
            })
        }
        
    }

    deleteItem(index){
        const list=[...this.state.list];
        list.splice(index,1);//从数组中删除指定index的数据
        this.setState({
            list
        })
    }

    getList(){
        return this.state.list.map((item,index)=>{
            return (
                <TodoItem 
                    item={item}
                    key={index}
                    index={index}
                    deleteItem={this.deleteItem}
                />
            )
        })
    }

    render(){
        // 这是JS中的注释
        return (
            <Fragment>
                {/* 这是JSX中的注释 */}
                <label htmlFor="input">请输入内容:</label>
                <input type="text" 
                    id="input"
                    className="input"
                    value={this.state.inputVal} 
                    onChange={this.changeVal} 
                    onKeyUp={this.addItem} 
                />
                <ul>{this.getList()}</ul>
            </Fragment> 
        );
    }
}

export default TodoList;

自组件 TodoItem.js

import React,{Component} from 'react';

class TodoItem extends Component{
    constructor(props){
        super(props);
        this.deleteItem=this.deleteItem.bind(this);
    }

    deleteItem(){
        //调用父组件传递过来的方法
        //this.props.deleteItem(this.props.index);
        //解构赋值写法
        const {deleteItem,index}=this.props;
        deleteItem(index);
    }

    render(){
        return <li key={this.props.index} onClick={this.deleteItem}>{this.props.item}</li>
    }
}

export default TodoItem;

效果图

猜你喜欢

转载自www.cnblogs.com/chenyingying0/p/12687819.html