美文网首页
(二十四)无状态组件

(二十四)无状态组件

作者: 云凡的云凡 | 来源:发表于2020-11-01 23:03 被阅读0次

    完善一下(二十三) 的 TodoListUI.js UI 组件

    1.无状态组件 在什么时候用?

    当一个组件只有render函数时,就可以写成 无状态组件
    无状态组件:其实就是一个函数,这个函数会接收一个参数叫 props,也就是父组件传递 过来的内容,同时返回一个 JSX,jsx中使用 props 就不要this.props 了,直接用props

    image.png

    只改了 TodoListUI.js 文件-把 普通组件 注释了

    // import React, { Component } from 'react';
    import React from 'react';
    import { Input, Button, List } from 'antd';
    
    // 无状态组件
    const TodoListUI = (props) => {
        return (
            <div style={{ marginTop: '10px', marginLeft: '10px' }}>
                <div>
                    <Input value={props.inputValue} placeholder="todo info" style={{ width: '300px', marginRight: '10px' }} onChange={props.handleInputChange} />
                    <Button type="primary" onClick={props.handleBtnClick}>提交</Button>
                    <List style={{ marginTop: '10px', width: '300px' }}
                        bordered
                        dataSource={props.list}
                        renderItem={(item, index) => (
                            <List.Item onClick={() => { props.handleItemDelete(index) }}>
                                {item}
                            </List.Item>
                        )}
                    />
                </div>
    
            </div>
        )
    }
    
    
    // 普通组件
    // class TodoListUI extends Component {
    //     render() {
    //         return (
    //             <div style={{ marginTop: '10px', marginLeft: '10px' }}>
    //                 <div>
    //                     <Input value={this.props.inputValue} placeholder="todo info" style={{ width: '300px', marginRight: '10px' }} onChange={this.props.handleInputChange} />
    //                     <Button type="primary" onClick={this.props.handleBtnClick}>提交</Button>
    //                     <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>
    
    //             </div>
    //         )
    //     }
    // }
    export default TodoListUI
    
    2.无状态组件 相对于 普通组件 的优势是什么?

    无状态组件性能比普通组件高:因为它就是一个函数,而 普通组件 是一个js里的类,这个类生成的对象里面还会有一些生命周期函数,普通组件执行起来既要执行render、又要执行生命周期函数,所以普通组件执行的东西远比函数多

    3.一般在什么时候用 无状态组件?

    当我们在定义 UI组件的时候,它只负责页面的渲染、没有去做任何的逻辑操作的时候,UI组件 一般可以用 无状态子组件来定义。

    E:\20201017-React\redux-todolist\ui-container-component\todolist
    需要完整代码,加我微信: hello_helloxi

    相关文章

      网友评论

          本文标题:(二十四)无状态组件

          本文链接:https://www.haomeiwen.com/subject/vkpdmktx.html