简体   繁体   English

在闭包中调用类函数 React Native

[英]Call class function inside a closure React native

I'm new to React native, and got a problem here, I want to use closure instead of lambda at onChangeText function:我是 React Native 的新手,在这里遇到了一个问题,我想在onChangeText函数中使用闭包而不是 lambda:

render() {
        return (
            <View style={{padding: 10}}>
                <TextInput style={{height: 40}} placeholder="Type here"
                           onChangeText = {function(t) {
                            this.setState({text: t});
                           }}
                          // onChangeText={(text) => this.setState({text: text})}
                />
                <Text style={{padding: 10, fontSize: 42}}>
                    {this.state.text.split(' ').map((word) => word && '🍕').join(' ')}
                </Text>
            </View>
        );
    }

The problem is inside the closure, this is the closure context, not the class context, so I can't call setState there.问题出在闭包内部, this是闭包上下文,而不是类上下文,所以我不能在那里调用setState In Java, I just simply remove this and everything OK, but how can I do this in JS?在 Java 中,我只是简单地删除它,一切正常,但是我如何在 JS 中做到这一点?

You can use JavaScript's bind method .您可以使用 JavaScript 的bind 方法

Assuming your desired function is already a method on your class.假设您想要的函数已经是您类中的一个方法。 ie: IE:

class MyClass extends React.Component {

  myMethodThatChangesState() {
    this.setState(...);
  }

  render() {...}
}

React requires pure functions. React 需要纯函数。 To avoid using lambdas such as:避免使用 lambda 表达式,例如:

onChangeText={() => this.setState(..)}

Bind your method to your class through JavaScript Function's bind method, like so:通过 JavaScript 函数的 bind 方法将您的方法绑定到您的类,如下所示:

onChangeText={myMethodThatChangesState.bind(this)}

Using Function.bind(this) returns a function with the this as the last argument - so the this will be your React class.使用Function.bind(this)返回一个以this作为最后一个参数的函数 - 所以this将是你的 React 类。 ES6 arrow functions perform the same action. ES6 箭头函数执行相同的操作。

This way you can avoid using arrow functions in your render markup.这样您就可以避免在渲染标记中使用箭头函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM