React中UI组件和容器组件的拆分

2022-03-19  本文已影响0人  泡杯感冒灵
UI组件,也叫傻瓜组件,负责页面的渲染。
容器组件,也叫聪明组件,负责处理逻辑。
拿todolist组件举例,todolist组件如何渲染,是有render函数决定的,todolist组件的逻辑,也都是写在这个组件中。当我们把组件的渲染和逻辑,都写在一个文件里的时候,后期的内容会比较多,维护会比较困难。于是我们需要对这个组件进行拆分,其中UI组件负责组件的渲染,容器组件负责组件的逻辑。
import React,{Component} from 'react';
import 'antd/dist/antd.css';
import { Input,Button,List } from 'antd';

class TodoListUI extends Component {
    render(){
        return (
            <div style={{margin:'10px'}}>
                <div>
                    <Input 
                        value={this.props.inputValue}  
                        placeholder="todo info" 
                        style={{width:'300px',marginRight:'10px'}}
                        onChange={this.props.handleInputChange}
                    >
                    </Input>
                    <Button 
                        type="primary"
                        onClick={this.props.handleBtnClick}
                    >
                        提交
                    </Button>
                </div>
                <List
                    style={{marginTop:'10px',width:'300px'}}
                    bordered
                    dataSource={this.props.list}
                    renderItem={(item,index) => (<List.Item onClick={()=> {this.props.handleItemDelete(index)}}>{item}</List.Item>)}
                />
            </div>
        )
    }
}

export default TodoListUI;
import React, {Component} from 'react';
import store from './store';
import {getInputChangeAction, getAddItemAction,getDeleteItemAction} from './store/actionCreators';
import TodoListUI  from './TodoListUI';

class TodoList extends Component {
    constructor(props){
        super(props);
        this.state = store.getState();
        this.handleInputChange = this.handleInputChange.bind(this);
        this.handleStoreChange = this.handleStoreChange.bind(this);
        this.handleBtnClick = this.handleBtnClick.bind(this);
        this.handleItemDelete = this.handleItemDelete.bind(this);
        store.subscribe(this.handleStoreChange);
    }
    render(){
        return (
            <TodoListUI 
                 inputValue = {this.state.inputValue}
                 list = {this.state.list}
                 handleInputChange = {this.handleInputChange}
                 handleBtnClick = {this.handleBtnClick}
                 handleItemDelete = {this.handleItemDelete}
                />
            );
    }
    handleInputChange(e){
        const action = getInputChangeAction(e.target.value);
        store.dispatch(action);
    }
    handleStoreChange(){
        this.setState(store.getState());
    }
    handleBtnClick(e){
        const action = getAddItemAction();
        store.dispatch(action);
    }
    handleItemDelete(index){
        const action = getDeleteItemAction(index);
        store.dispatch(action);
    }
}

export default TodoList;
上一篇 下一篇

猜你喜欢

热点阅读