简体   繁体   中英

I got the error when calling a function with param

onTypeSelect (str) {
        this.setState({taskType: str})
    }

<TouchableOpacity onPress={this.onTypeSelect('type1').bind(this)}>
</TouchableOpacity>

undefined is not an object (evaluating '_this3.onTypeSelect('type1).bind').

Can anyone help me? I am a beginner of react-native.

Try this

onTypeSelect (str) {
    this.setState({taskType: str})
}

<TouchableOpacity onPress={() => { this.onTypeSelect('type1'); }} />

When you .bind(this), you need to pass a function and not the return value of a function, in this case, undefined . This way it works because the function is called from inside the component scope thus making this a valid reference.

Another way to fix the problem is by using bind this way:

this.onTypeSelect.bind(this, 'type1')

EDIT: Thanks for the comments and other replies, I added the information for sake of completion and information. Alexander T. , Bartek F.

Based on .bind docs, you have to pass arguments to .bind like so

this.onTypeSelect.bind(this, 'type1')

fun.bind(thisArg[, arg1[, arg2[, ...]]])

In your example, you call method

this.onTypeSelect('type1')

the method returns result (in this case result will be undefined ), and you are trying to apply .bind to result ( undefined )

undefined.bind(this)

However .bind exists only in Function object, that's why you get the error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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