美文网首页
React Native 函数的绑定

React Native 函数的绑定

作者: 冷洪林 | 来源:发表于2017-01-10 10:15 被阅读192次

在ES6的class中函数不再被自动绑定,你需要手动去绑定它们。

第一种在构造函数里绑定。

  constructor(props) {
    super(props); 
    // Set up initial state
    this.state = {
        text: props.initialValue || 'placeholder' 
};
    // Functions must be bound manually with ES6 classes
    this.handleChange = this.handleChange.bind(this); 

另一种方式就是在你使用的地方通过内联来绑定:

// Use `.bind`:
 render() { 
    return (
     <input onChange={this.handleChange.bind(this)}
     value={this.state.text} /> 
);
}
// Use an arrow function:
render() {
     return (
        <input onChange={() =>  this.handleChange()} 
    value={this.state.text} />
);

以上任意一种都可以,然而在效率上却不行了。每一次调用render(可以说是非常频繁!)一个新的函数都会被创建。与在构造函数里只绑定一次相比就慢一些。

最终的选择是使用箭头函数直接替换函数在类中的声明,像这样:

// the normal way
// requires binding elsewhere
handleChange(event) {
    this.setState({
    text: event.target.value
    });
}
// the ES7 way
// all done, no binding required
handleChange = (event) => { 
  this.setState({
text: event.target.value
  });
}

通过这种方式,你不需要绑定任何东西。这都已经通过神奇的箭头函数被搞定了。像期望的那样,函数内部的this将会指向组件实例。参考:http://www.jianshu.com/p/a4c23654932e

相关文章

网友评论

      本文标题:React Native 函数的绑定

      本文链接:https://www.haomeiwen.com/subject/jxjkbttx.html