我收到老板的要求,要分析我同事的现有代码。我遇到了一些像这样的奇怪代码:
class Parent extends React.Component {
methodA () { ... }
methodB () { ... }
render () {
<div>
...other lines of code
<Child parent={this} />
</div>
}
}
在子组件内部,他们使用 this.props.parent.methodA() 和其他类似的父方法,而不是将函数作为 props 传递。
我提议一条不使用该模式的规则。因为这非常难读,而且这些函数的行为有时可能无法预测。
我想知道除了我正在谈论的事情之外,这种模式是否会遇到任何性能问题?
提前致谢。
最佳答案
例如,最常见的情况是子级在单击事件时从父级调用某些方法。 在那种情况下,您只传递该方法。
<Child doSomethingMethod={methodA} />
然后在 Child
的渲染方法中:
<button onClick={doSomethingMethod} />
我想不出一个 child 应该知道 parent 实现的例子。
在您的情况下,父级应始终具有 methodA
并且如果您决定要更改父级结构,则还需要更改子级。
另一方面,当你只传递一个方法时,你的 child 不关心 parent 从哪里得到那个方法。因此,它是松散耦合的,其中每个组件仅处理自身,并且仅从它需要的其他组件(包括函数)接收那些参数。
关于javascript - react : Should I pass this reference of parent component to child component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59044079/