javascript – React 16.3类方法与构造函数方法
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – React 16.3类方法与构造函数方法,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1855字,纯文字阅读大概需要3分钟。
内容图文
我正在学习React 16.3,它是新的Context API.特别是Updating Context from a Nested Component.在他们的示例中,他们设置了一个在构造函数中定义的方法,而不是标准方法.
class App extends React.Component {
constructor(props) {
super(props);
// What is the benefit of doing this here?
this.toggleTheme = () => {
this.setState(state => ({
theme:
state.theme === themes.dark
? themes.light
: themes.dark,
}));
};
this.state = {
theme: themes.light,
toggleTheme: this.toggleTheme,
};
}
render() {
// The entire state is passed to the provider
return (
<ThemeContext.Provider value={this.state}>
<Content />
</ThemeContext.Provider>
);
}
}
我已经阅读的有关提升状态和将方法传递给孩子的所有内容都使用以下模式完成.为什么以上优先于以下?有什么不同吗?
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
theme: themes.light,
toggleTheme: this.toggleTheme,
};
this.toggleTheme = this.toggleTheme.bind(this);
}
// Could it be done here?
toggleTheme() {
this.setState(state => ({
theme:
state.theme === themes.dark
? themes.light
: themes.dark,
}));
};
render() {
// The entire state is passed to the provider
return (
<ThemeContext.Provider value={this.state}>
<Content />
</ThemeContext.Provider>
);
}
}
解决方法:
如果你使用第一种方法在构造函数中定义方法,就像这样
constructor() {
this.toggleTheme = () => {
this.setState(state => ({
theme:
state.theme === themes.dark
? themes.light
: themes.dark,
}));
};
}
然后,当你的组件使用this.toggleTheme作为回调时,你不必将它的引用绑定到定义它的当前组件,例如this.toggleTheme = this.toggleTheme.bind(this),另一方面,如果你将toggleTheme定义为构造函数之外的方法,如第二个例子中所示,并且如果toggleTheme作为回调传递,你将得到“setState不是在调用toggleTheme时定义“或类似的东西”
此外,使用第一种方法toggleTheme作为实例属性添加到组件类中,这意味着每个组件实例将具有toggleTheme的单独副本,而第二种方法将其添加到组件类的原型中,这在内存方面更好消费,因为所有组件实例将在原型上共享该方法
内容总结
以上是互联网集市为您收集整理的javascript – React 16.3类方法与构造函数方法全部内容,希望文章能够帮你解决javascript – React 16.3类方法与构造函数方法所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。