Search code examples
javascriptreact-nativetcomb

Disable a field based on another field's value


I am trying to implement a basic feature to disable a field based on another field's value. Here is the code sample:

import React from 'react'
import t from "tcomb-form-native";
import {Text, View, TextInput, TouchableHighlight } from 'react-native';

const Form = t.form.Form;

var Type = t.struct({
  disable: t.Boolean, // if true, name field will be disabled
  name: t.String
});

var options = {
  fields: {
    name: {}
  }
};

export default class App extends React.Component {

  constructor(props){
    super(props);
    this.state = {
      options: options,
      value: null
    }
  }

  onChange(value) {
    var newOptions = t.update(this.state.options, {
      fields: {
        name: {
          editable: {'$set': !value.disable}
        }
      }
    });
    this.setState({options: newOptions, value: value});
  }

  onPress() {
    var value = this.refs.form.getValue();
    if (value) {
      console.log(value);
    }
  }

  render() {
    return (
      <View style>
        <Form
          ref="form"
          type={Type}
          options={this.state.options}
          value={this.state.value}
          onChange={this.onChange}
        />
        <TouchableHighlight style onPress={this.onPress} underlayColor='#99d9f4'>
          <Text style>Save</Text>
        </TouchableHighlight>
      </View>
    )
  };

}; 

When I run the given code i run into the following error TypeError: undefined is not an object (evaluating 'this.state.options'). It is a really basic example as I am still a newbie and I am trying to understand how this code sample really works. Any help is appreciated. Thanks.


Solution

  • es6 classes don't autobind, if you use a property initializer it will scope this to your class:

    onChange = (value) => {
      //
    }