在使用Redux的时候,我们将页面渲染部分(即render
函数)和页面逻辑部分都放在了一个组件中。
为了便于维护,我们可以将页面渲染单独拿出来放到一个文件中,用来做纯页面渲染部分,这种组件叫UI组件。而剩下的实现页面逻辑的组件叫做容器组件
1.新建一个UI文件
2.将TodoList中的渲染部分移动到TodoListUI.js中
其中循环渲染部分参考我的另一篇博客:
使用Redux并借助Ant Design的List.Item时循环渲染传参的三种写法
//*UI组件只负责渲染*/
import React, {Fragment} from "react";
import TodoItem from "./TodoItem"; // 使用子组件
import 'antd/dist/antd.css'; // 导入样式
import {Input, Button, List} from 'antd'; // 导入组件
class TodoListUI extends React.Component {
render() {
return (
<Fragment>
<div style={{marginTop: '10px', marginLeft: '10px'}}>
<Input
style={{width: '300px'}}
id='insertArea'
className="input"
value={this.props.inputValue}
placeholder={'todo info'}
onChange={this.props.handleInputChange}
/>
<Button type="primary" onClick={this.props.handleBtnClick}>submit</Button>
<List
style={{marginTop: '10px', width: '300px'}}
bordered
dataSource={this.props.list}
renderItem={(item,index) =>(
<TodoItem
index={index}
delItem={this.props.handleItemDelete}
con={item}
/>
)
}
/>
</div>
</Fragment>
)
}
}
export default TodoListUI;
3.在TodoList组件中使用UI组件
TodoList组件中的render函数实现如下(父子组件传值的思想):
render() {
return (
<TodoListUI
inputValue={this.state.inputValue}
list={this.state.list}
handleInputChange={this.handleInputChange}
handleBtnClick={this.handleBtnClick}
handleItemDelete={this.handleItemDelete}
/>
);
}
项目地址:UI组件
当一个普通组件只有render
函数时,就可以用无状态组件来替换,无状态组件就是一个函数,优点是:性能高。无状态组件就是一个普通函数,不需要执行普通组件中含有的生命周期函数。
因此可以把TodoListUI中的代码做修改:
//*UI组件只负责渲染*/
import React, {Fragment} from "react";
import TodoItem from "./TodoItem";
import 'antd/dist/antd.css'; // 导入样式
import {Input, Button, List} from 'antd'; // 导入组件
const TodoListUI = (props) =>{ // 接收的props参数是父组件传递过来的
return (
<Fragment>
<div style={{marginTop: '10px', marginLeft: '10px'}}>
<Input
style={{width: '300px'}}
id='insertArea'
className="input"
value={props.inputValue}
placeholder={'todo info'}
onChange={props.handleInputChange}
/>
<Button type="primary" onClick={props.handleBtnClick}>submit</Button>
<List
style={{marginTop: '10px', width: '300px'}}
bordered
dataSource={props.list}
renderItem={(item,index) =>(
<TodoItem
index={index}
delItem={props.handleItemDelete}
con={item}
/>
)
}
/>
</div>
</Fragment>
)
}
export default TodoListUI;