据我所知,在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'));
在上面的代码段中,有{strong>两种方式从callMe()
调用ParentCont
上的MyButton
,
首先,将props
直接附加到事件处理程序,即Click Me A
按钮,
第二次,将所谓的local function
附加到事件处理程序,即Click Me B
按钮,
哪一个最好?或者彼此的优点和缺点是什么?
答案 0 :(得分:1)
如果可以的话,你想传递道具功能。它运行效率更高,代码更少。使用调用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>
)
}
}
或者如果子类具有本地状态,您可能希望通过它。
如果不需要传递变量,那么你不需要本地函数。注意我删除了绑定。你不想在渲染中的任何处理程序上绑定或使用内联箭头函数,因为它会导致性能下降。