![](/img/trans.png)
[英]What is the best way to call a method in a controller from a service in angular?
[英]What is the best way to call inherited method (through 'props') on ReactJS?
据我所知, 在ReactJS上有两种主要的调用继承方法的模式 ,但是我不知道应该使用哪种方法,或者是最佳实践,
class ParentCont extends React.Component {
constructor(props) {
super(props);
this.state = {
myState : "My State"
}
}
callMe() {
console.log(this.state.myState);
}
render() {
return(
<div>
<MyButton myProp={this.callMe.bind(this)} />
</div>
)
}
}
class MyButton extends React.Component {
buttonB() {
this.props.myProp();
}
render() {
return(
<div>
<button onClick={this.props.myProp}>Click Me A</button>
<button onClick={this.buttonB.bind(this)}>Click Me B</button>
</div>
)
}
}
ReactDOM.render(<ParentCont />, document.getElementById('app'));
在以上代码段中,有两种方法可以从MyButton
在ParentCont
上调用callMe()
,
首先 ,将props
直接附加到事件处理程序,即Click Me A
按钮,
其次 ,将所谓的local function
附加到事件处理程序,即Click Me B
按钮,
哪一个是最好的? 或彼此的优缺点是什么?
您想通过prop函数。 它效率更高,运行的代码更少。 使用局部函数调用prop函数的全部目的是要使用其他信息或局部信息来影响对该函数的调用。 例如
class MyButton extends React.Component {
buttonB = () => {
this.props.myProp(this.props.id);
}
render() {
return(
<div>
<button onClick={this.buttonB}>Click Me B</button>
</div>
)
}
}
或者,例如,如果子类具有本地状态,则您希望通过它。
如果不需要传递变量,则不需要局部函数。 请注意,我删除了绑定。 您不想在渲染器中的任何处理程序上绑定或使用嵌入式箭头功能,因为它会导致性能下降。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.