mojizo
mojizo

Reputation: 37

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.

Upvotes: 0

Views: 94

Answers (2)

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.

Upvotes: 3

Oleksandr T.
Oleksandr T.

Reputation: 77482

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.

Upvotes: 2

Related Questions