组件UI和业务逻辑的拆分
将组件中所用数据和方法通过props传给子UI组件,子UI组件调用这些数据和方法完成页面渲染(业务逻辑层的构造函数不变)
TodtListUI.js
import React, { Component } from 'react' import {Input,Button,List} from 'antd' class TodoListUI extends Component { render() { return ( <div style={{margin:'10px'}}> <div><Input placeholder={this.props.inputValue} style={{width:'250px',marginRight:'10px'}} onChange={this.props.changeInputValue} value={this.props.inputValue} /> <Button type='primary' onClick={this.props.clickBtn} >增加</Button> </div> <div style={{margin:'10px',width:'300px'}}> <List bordered dataSource={this.props.list} // renderItem={(item,index)=>(<List.Item onClick={this.deleteItem.bind(this,index)}>{item}</List.Item>)} //该行index不能放到方法中,删除功能有问题,待改进删除方法里的index参数即可 renderItem={(item,index)=>(<List.Item onClick={()=>{this.props.deleteItem(index)}}>{item}</List.Item>)} /> </div> </div> ); } } export default TodoListUI;
Todolist.js
import React, { Component } from 'react' import store from './store'; import { changeInputAction,addItemAction,deleteItemAction } from './store/actionCreators'; import TodoListUI from './TodoListUI'; class TodoList extends Component { constructor(props){ super(props) this.state=store.getState() this.changeInputValue=this.changeInputValue.bind(this) this.storeChange=this.storeChange.bind(this) this.clickBtn=this.clickBtn.bind(this) //ui拆分 this绑定处理 this.deleteItem=this.deleteItem.bind(this) // store.subscribe(this.storeChange)//订阅 } componentDidMount(){ store.subscribe(this.storeChange) //订阅 } render() { return ( <TodoListUI inputValue={this.state.inputValue} changeInputValue={this.changeInputValue} clickBtn={this.clickBtn} list={this.state.List} deleteItem={this.deleteItem} /> ); } storeChange(){ this.setState(store.getState()) } changeInputValue(e){ //e:改变的值都可以监听到 //console.log(e.target.value) // const action={ // type:CHANGE_INPUT, // value:e.target.value // } const action=changeInputAction(e.target.value) store.dispatch(action) } clickBtn(){ // const action ={type:ADD_ITEM} // store.dispatch(action) const action=addItemAction() store.dispatch(action) } deleteItem(index){ console.log("111:"+index) // const action ={ // type:DELETE_ITEM, // index // } const action=deleteItemAction(index) store.dispatch(action) } } export default TodoList;
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?