Reputation: 1415
I just began playing around with React Native and I was trying to figure out how to disable and enable a touchableOpacity when the lengths of two inputTexts are > 0.
On my touchableOpacity I have it set to disabled={true} and it has a children Text with opacity set. When a user types into the textInput's I want to set disabled={false} and change the Text opacity to 1.
What's the best way to do this in react native?
Should i put ref's on them?
Should I use a className?
setNativeProps maybe?
Upvotes: 0
Views: 1489
Reputation: 105
If your constructor's state contains a flag for "isDisabled" and "textOpacity", then you can call setState in the onChangeText function that will change the state of isDisabled and textOpacity. The text component can use the opacity from the state's textOpacity and the touchableOpacity can use the state's isDisabled.
Ex:
`class foo extends Component {
constructor(props) {
super(props);
this.state = {
isDisabled: true,
textOpacity: 0.1,
text1: '',
text2: '',
};
onTextChange1(text) {
if (text.length > 0 && this.state.text2.length > 0) {
this.setState({isDisabled: false, textOpacity: 1, text1: text});
}
else {
this.setState({isDisabled: true, textOpacity: 0.1, text1: text});
}
}
onTextChange2(text) {
if (text.length > 0 && this.state.text1.length > 0) {
this.setState({isDisabled: false, textOpacity: 1, text2: text});
}
else {
this.setState({isDisabled: true, textOpacity: 0.1, text2: text});
}
}
render() {
return (
<View>
<TextInput onChangeText={(text) => this.onTextChange1(text)} value={this.state.text1}/>
<TextInput onChangeText={(text) => this.onTextChange2(text)} value={this.state.text2}/>
<TouchableOpacity disabled={this.state.isDisabled}>
<Text style={{opacity:this.state.textOpacity}}>Hello World!</Text>
</TouchableOpacity>
</View>
);
}
}
I have not tested the above, but I believe this is basically what you are looking for. We perform a check in the on text change to see if a certain condition is met, and depending on if it is, we change the parameters of the child components as you stated. Calling setState and modifying props are the only ways to trigger a rerender, so this is how in react-native we work with rerendering components.
Upvotes: 1
Reputation: 397
if you want your opacity to be able to change depending on user moves, you need to set it(opacity) in state of your parent component.You can do this for example:
export class Parent extends React.Component {
constructor(props) {
super(props);
this.state = { opacity: 0 }
}
render() {
Some components ....
<TextInput style={{opacity: this.state.opacity}} onChangeText={ () => this.setState({opacity: 1}) } ...other props here .../>
Some components ....
}
}
you can also apply other styles to your TextInput
component.
Upvotes: 1