react在引入组件的时候对prop的书写那种方法比较好

我在github看代码以及antd, 发现有几种写法

写法1:

    render() {

        return (
            <div>
                <Tools {...propTools}/>
                <CreateModal
                    ref={(form) => {this.form = form}}
                    visible={this.state.visible}
                    onCancel={this.handleCancel}
                    onCreate={this.handleCreate}
                    onOk={this.handleCreate}
                />
            </div>
        );
    }

写法2:

    render() {
        const propCreateModal = {
            ref: (form) => {
                this.form = form
            },
            visible: this.state.visible,
            onCancel: this.handleCancel,
            onCreate: this.handleCreate,
            onOk: this.handleCreate,
        }
        return (
            <div>
                <Tools {...propTools}/>
                <CreateModal
                    {...propCreateModal}
                />
            </div>
        );
    }

第一种比较直观
第二种我没感觉出哪里好, 看具体的prop还要定位到声明的位置, 跳来跳去的, 很消耗人

阅读 2.5k
3 个回答

第一种写法好处:

  1. 贴近 HTML 语法和 Vue 的模板语法

  2. 可以不需要 rest 运算符

第二种写法好处:

  1. JSX 组件层次结构更清晰,尤其是在组件多、嵌套深、逻辑复杂情况下;

  2. 方便属性的复用,避免相同的组件重复配置:

     render() {
        const propCreateModal = {
            ref: (form) => {
                this.form = form
            },
            visible: this.state.visible,
            onCancel: this.handleCancel,
            onCreate: this.handleCreate,
            onOk: this.handleCreate,
        }
        
        const propCreateModal2 = Object.assign({}, propCreateModal, {
            visible: !this.state.visible
        })
        
        return (
            <div>
                <Tools {...propTools}/>
                <CreateModal
                    {...propCreateModal}
                />
                <CreateModal
                    {...propCreateModal2}
                />
            </div>
        );
    }

3.方便调试,可以在需要的时候将传入组件的属性打印出来:

console.log(propCreateModal)

两种写法各有好处,哪个好哪个差都不是绝对的。

新手上路,请多包涵

没有好坏之分,只是习惯问题。如果你喜欢保持jsx的整洁,那么第二种肯定要好些。

你的感觉是对的。第一种是标准,看官方文档就知道了。第二种画蛇添足,估计是有谁想重复利用prop最后弄得不伦不类,属于典型的OO思维。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题