【问题标题】:Where to put methods, inside parent or child components?在哪里放置方法,在父组件或子组件中?
【发布时间】:2019-11-16 23:14:10
【问题描述】:

我正在用 React 构建一个网站,我想知道在放置 JS 函数方面有什么更好的做法。如果我有一个方法doSomething() 并且在组件的多个实例中使用doSomething(),那么将doSomething() 放在子组件还是父组件中会更好吗?如果它在父组件中,它会使代码更难遵循,而如果它在子组件中,则会检索多个相同的方法(即每个调用的子组件实例一个)。

即这个更好吗:

export default class Parent extends Component{

    doSomething(){...}

    render(){
        return(
            <Child />
            <Child />
            <Child />
        ) }

}

或者这个:

export default class Parent extends Component{

    render(){
        return(
            <Child />
            <Child />
            <Child />
        ) }

}


class Child extends Component{

    doSomething(){...}

    render(){
        return(
            <p>This is the child component</p>
        )

    }

}

【问题讨论】:

  • 放在孩子里面

标签: javascript reactjs


【解决方案1】:

如果只在 Child 实例中使用,我会将方法放在 Child 类中。

“而如果它在子组件中,则会检索到多个相同的方法。”

您在上面的 child 中声明 doSomething() 的方式不会使其成为实例方法。

doSomething() 方法最终将成为 Child 原型的属性,其引用将被所有实例共享。

要使 doSomething 最终成为实例方法,您必须在 Child 构造函数中定义类似 this.doSomething = function(){... 的内容。

(另一个例外是如果您将 doSomething() 声明为 Child 类的构造函数的 static 方法)。

【讨论】:

    猜你喜欢
    • 2019-09-04
    • 2011-10-26
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 2020-03-10
    • 2011-04-08
    相关资源
    最近更新 更多