Mathew
Mathew

Reputation: 1460

react native, undefined is not an object (evaluating 'this.state.thing = input')

I am trying to set the onSubmitEditing function of a TextInput object to a custom function, here is my code:

export default class Component4 extends Component {
    constructor(props) {
        super(props);
        this.state = {thing: 'asdf'};
        this.func = this.func.bind(this);
    }

    func(input){
        this.setState({thing: input.target.value});
        // I will eventually do more complicated stuff
    }

    render(){
        return (
            <View style={{padding: 30}}>
                <TextInput placeholder="default" onSubmitEditing={this.func}/>
                <Text>{this.state.thing}</Text>
            </View>
        );
    }
}

I would like the content of the TextInput to be passed to the function 'func' so that it can change the state of 'thing'. I realize I can just use an arrow function to achieve this and skip having function entirely however like it says in the comment in func I intend to add more complex behaviour there. Thanks for the help

Upvotes: 1

Views: 3267

Answers (2)

mccambridge
mccambridge

Reputation: 1022

You have to bind your methods to the constructor. You also need a method/function to handle text changes as well as one to handle collecting a result. edit: I guess now that I understand what you're going for, the button was unnecessary.

export default class Component4 extends Component {
    constructor(props) {
        super(props);
        this.state = {myInput: '', myResult: ''};
        this.onChange = this.onChange.bind(this);
        this.onPress = this.onPress.bind(this);
    }

    onChange(input){
        this.setState({myInput: input.target.value});
        // I will eventually do more complicated stuff
    }

    onPress() {
        this.setState({myInput: '', myResult: this.state.myInput});
    }

    render(){
        return (
            <View style={{padding: 30}}>
                <TextInput name='myInput' placeholder="default" onChange={this.onChange}/>
                <Text>{this.state.myResult}</Text>
                <Button onPress={this.onPress} title='Click me!' />
            </View>
        );
    }
}

Upvotes: 1

nathan hayfield
nathan hayfield

Reputation: 2685

When you declare your function that way it doesn't have access to this because of scoping. Use es6 fat function to give it access to this. Also use setState function instead of direct assignment

func = (input) => {
  this.setState({thing: input});
  //more complicated stuff here
};

Also change TextInput to use onChange instead of onSubmitEdit

Upvotes: 2

Related Questions