如何编写一个可复用组件

将一个不可复用的组件改为清晰通用的可复用组件

class OneList extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            list: [],
        }
    }
    componentDidMount() {
        // 从api中加载一个消息列表
        fetch().then(list => {
            this.setState({ list })
        })
    }
    render() {
        const { list = [] } = this.state; 
        return (
            <ul>
                {
                    list.map(item => (
                        <li key={item.id}>
                            <div>{item.userName}</div>
                            {item.choice && <div>{item.choice}</div>}
                        </li>
                    ))
                }
            </ul>
        )
    }
}
复制代码

使用无状态组件复写一下这个列表api

const TwoList = ({ list = [] }) => (
    <ul>
        {
            list.map(item => (
                <li key={item.id}>
                    <div>{item.userName}</div>
                    {item.choice && <div>{item.choice}</div>}
                </li>
            ))
        }
    </ul>
)
复制代码

上面的组件是彻底能够知足正常工做须要的,可是遇到相同代码,再去复制代码每每不是最佳解决方案,可是可能会由于代码量少而不去对组件进行抽象和须要展现的数据进行解耦数组

编写一个可复用的List组件

这里的List组件不会包含状态,因此能够将其改写为无状态的函数组件bash

const List = ({ list, userNameKey, choiceKey  }) => (
// userName 用于指定须要显示的属性名,choice用于指定可选部分的属性
    <ul>
        {
            list.map(item => (
                <Item 
                    key={item.id}
                    userName={item[userNameKey]}
                    choice={item[choiceKey]}
                />
            ))
        }
    </ul>
)
const Item = ({ userName, choice }) => (
    <li>
        <div>{userName}</div>
        {choice && <div>{choice}</div>}
    </li>
)
复制代码

如今咱们建立了两个接口清晰的小型组件,优势:容易维护与测试,fix bug 更方便函数

使用组件

OneList测试

render() {
    return (
        <List
            list={list}
            userNameKey='userName'
            choiceKey='choice'
        />
    )
}
复制代码

TwoListfetch

const TwoList = ({ list }) => (
    <List
        list={list}
        userNameKey='userName'
        choiceKey='choice'
    />
)
复制代码

如今已经完成了组件的建立,将一个单一需求的组件变得可复用,若是有新的需求,咱们只须要改动一点代码就能完成全部地方的修改ui


相比冬天的砖,我仍是喜欢秋天的砖,不那么冻手···this

相关文章
相关标签/搜索