我明白,在ES6我必须手动绑定每个上下文方法。
是的,除非这不完全正确。 ES6允许你表达比ES5更好的东西。
在ES6中编写代码并不意味着您直接翻译了ES5中的代码。使用当前版本的React中的新功能以及ES6原生的功能,有更多的惯用方法可以实现它。
import {Component} from 'react'
class Foo extends Component {
// this class doesn't even need constructor
createButton(text) {
// don't write
// return <button onclick={this.handleClick.bind(this)}>{text}</button>
// instead write
return <button onclick={e=> this.handleClick(e)}>{text}</button>
}
handleClick(event) {
console.log(event, 'button was clicked')
}
render() {
var {buttons} = this.props;
// don't write
// return <div>{buttons.map(this.createButton.bind(this)}</div>
// instead write
return <div>{buttons.map(this.createButton, this)}</div>
}
}
export default Foo;
// <Foo buttons={["one", "two", "three"]} />
通知我用两种不同的方式背景下,并不需要有一个词汇this
因此具有约束力并不在大多数情况下需要Function.prototype.bind
- 箭头功能。箭头功能是ES6的新功能。
Array.prototype
功能像map
,reduce
,forEach
接受thisArgument
,它允许您更改回调的背景下。这对于ES6来说并不陌生,所以今天在ES5代码中没有什么能阻止你使用它。
但是你也看到这是一个stateless functional component?无状态的功能组件可作为阵营0.14
在惯用的阵营代码,大多数你写会是无状态的,只是构成其他组件的组件。我们正在推出一个新的,更简单的语法为这些组件,您可以采取的道具作为参数,并返回要渲染的元素
来源:React Blog v0.14
这段代码功能相同以上,但该组件不需要class
或上下文仪式
const createButton = (text) => {
return <button onClick={handleClick}>{text}</button>
}
const handleClick = (event) => {
console.log(event, 'button was clicked')
}
// stateless functional component
const Foo = ({buttons}) => {
return <div>{buttons.map(createButton)}</div>
}
export default Foo;
当然,这种方法不能用于组件的工作,我nvolve state
(或生命周期方法),但它适用于任何仅使用props
的组件 - 这是您的大部分组件。
这只是一个技巧,你必须以一种惯用的方式编写React应用程序,不涉及Function.prototype.bind
。
对于它的价值,我已经多年没有依赖Function.prototype.bind
(有我写的代码)。
我建议你看看我的答案,即使@naomik downvoted和标记为删除。这是直接来自Facebook的解决方案,并解释了原因。 – mtaube