I have this factory:
import React, {PropTypes} from 'react';
import {View, Text, StyleSheet} from 'react-native';
import ColorPicker from 'react-native-theme-picker'
var t = require('tcomb-form-native');
var Component = t.form.Component;
class tColorPicker extends Component {
static propTypes = {
options: PropTypes.shape({
themes: React.PropTypes.array
})
}
constructor(props) {
super(props);
if (props.options.themes) {
this.themes = this.themes;
}
else {
this.themes = this.generateRandomColors();
}
}
generateRandomColors() {
var colors = [];
for (let i = 0; i <= 10; i++) {
// Generate HEX values
// https://www.paulirish.com/2009/random-hex-color-code-snippets/
colors.push('#' + '0123456789abcdef'.split('').map(function (v, i, a) {
return i > 5 ? null : a[Math.floor(Math.random() * 16)]
}).join('')
);
}
return colors;
}
getTemplate() {
return (locals) => {
var stylesheet = locals.stylesheet;
var controlLabelStyle = stylesheet.controlLabel.normal;
if (locals.hasError) {
controlLabelStyle = stylesheet.controlLabel.error;
}
var label = locals.label ? <Text style={controlLabelStyle}>{locals.label}</Text> : null;
return (
<View>
{label}
<ColorPicker
size={30}
colors={this.themes}
selectedColor={this.state.value}
onSelected={(color)=>this.setState({value: color})}/>
</View>
);
}
}
}
export default tColorPicker;
this is how my component is rendering the form and acting on the onChange event:
onChange(value) {
var today = moment();
var sown = moment(this.refs.form.getComponent('sown').props.value);
this.setState({
...value,
cropAge: today.diff(sown, 'days')
});
}
render() {
const cropAge = <Text>Kulturalter: {this.state.cropAge} Tage </Text>
return (
<ScrollView style={{marginTop: 60}} keyboardShouldPersistTaps={true} keyboardDismissMode="interactive">
<KeyboardAvoidingView behavior="padding" style={{paddingLeft: 20, paddingRight: 20}} >
<Form
ref="form"
type={CropModel.model}
options={CropModel.options}
value={this.state}
onChange={this.onChange.bind(this)}
/>
{cropAge}
</KeyboardAvoidingView>
</ScrollView>
)
}
}
As you can see in the onchange event I'm getting the sown date and I'm calculating how long ago that was. After that I rerender the form.
The problem is that when my form displays and I manipulate the colors the form doesn't trigger onChange event. So my state has color: ''. So when I go in a field and type something the form triggers an onchange event and my form rerenders and my selected value for my color is reset.
What is the correct way to trigger onChange event on the form?
Ok, I have finally figured this out. Tcomb seems to pass an onChange prop. So, all I have to do in my onSelected event is to trigger the this.props.onChange(value); event and other components will know about the change.
Most helpful comment
Ok, I have finally figured this out. Tcomb seems to pass an onChange prop. So, all I have to do in my onSelected event is to trigger the this.props.onChange(value); event and other components will know about the change.