我刚接触使用带有React的ES6类,之前我已经将我的方法绑定到当前对象(在第一个示例中显示),但ES6是否允许我使用箭头将类函数永久绑定到类实例?(当作为回调函数传递时很有用.)当我尝试使用它时,我遇到错误,就像使用CoffeeScript一样:
class SomeClass extends React.Component {
// Instead of this
constructor(){
this.handleInputChange = this.handleInputChange.bind(this)
}
// Can I somehow do this? Am i just getting the syntax wrong?
handleInputChange (val) => {
console.log('selectionMade: ', val);
}
Run Code Online (Sandbox Code Playgroud)
因此,如果我要传递SomeClass.handleInputChange给setTimeout它,那么它将被限定为类实例,而不是window对象.
我有一个使用react-native创建的登录屏幕.
当用户输入textInput时,如何将屏幕移开?
我是否会听取onFocus()事件并使用css样式来更改视图的样式?
在创建React类时,哪个更好?
export default class Foo extends React.Component {
constructor (props) {
super(props)
this.doSomething = this.doSomething.bind(this)
}
doSomething () { ... }
}
Run Code Online (Sandbox Code Playgroud)
要么
export default class Foo extends React.Component {
doSomething = () => { ... }
}
Run Code Online (Sandbox Code Playgroud)
我的同事认为后者会导致内存问题,因为babel会将代码转换为捕获this内部的代码,并且该引用将导致实例不被GC清除.
有什么想法吗?
我在我的JSX中有这个:
<Options options={options} onOptionSelect={this.onOptionSelect.bind(this)} />
Run Code Online (Sandbox Code Playgroud)
但是,我发誓我已经看到了一些幻想,否定了.bind将回调方法传递给子React组件时的需要,我是对的吗?