一、在容器组件中拆分出UI组件
上一篇中说到的Todolist.js
就是容器组件,它的render方法
中返回了很多的UI组件
,所以有必要把他们拆分一下
src根目录下新建一个TodolistUI.js
文件,将所有的UI组件放在这里面
拆分后,UI组件里面的this.state
都无法获取到了,这时就需要父组件(即容器组件)将this.state
和方法
作为参数,传递给UI组件
Todolist.js:
render() {
return (
//将this.state、方法都作为参数传递给UI组件
<TodolistUI
inputValue={
this.state.inputValue}
list={
this.state.list}
handleInputChange={
this.handleInputChange}
handleBtnClick={
this.handleBtnClick}
handleDeleteClick={
this.handleDeleteClick}
/>
);
}
TodolistUI.js:
import React, {
Component, Fragment } from 'react';
import {
Input, Button, List } from 'antd';
class TodolistUI extends Component {
render() {
return (
<Fragment>
<Input
placeholder='placeholder'
value={
this.props.inputValue}
onChange={
this.props.handleInputChange}
/>
<Button
type="primary"
onClick={
this.props.handleBtnClick}
>提交</Button>
<List
header={
<div>Header</div>}
footer={
<div>Footer</div>}
bordered
dataSource={
this.props.list}
renderItem={
(item, index) => (
<List.Item
onClick={
() => {
this.props.handleDeleteClick(index)
}}
>
{
item}
</List.Item>
)}
/>
</Fragment>
);
}
}
export default TodolistUI;
UI组件中,需要将原先所有的this.state
换成this.props
,将原先的this.方法名
换成this.props.方法名
注意:如果此时仍需要向方法传递一个参数,比如:index,就不能直接写成这种形式:onClick={this.props.handleDeleteClick(index)}
,要改写成这种形式:
onClick={
() => {
this.props.handleDeleteClick(index)
}}
二、无状态组件改写成函数
无状态组件
从字面来理解,就是没有state
的组件,这样的组件只有一个render
方法。
实际使用的时候最好改写成一个函数,将render
的return
改写成一个函数的return
。
这样改写的好处就是提高性能
,毕竟创建一个函数比创建一个类性能上要有所提高。
假设有一个无状态组件
:
class Todolist extends React.Component {
render() {
return (
//..
);
}
}
那么就可以将其改写成: