otusweb
otusweb

Reputation: 1678

passing props to child item and overriding some

I'm new to React Native and i'm trying to create a TextInput that I can style based on the focus state of the textInput. My understanding is that subclassing is not big in react, so i'm trying the approach of creating a component containing the text input.

So I created this component:

class FocusTextInput extends React.Component<{}, { isFocused: boolean }> {
  constructor(props: {}) {
    super(props);
    this.state = { isFocused: false };
  }
  onFocus() {
    this.setState({ isFocused: true });
  }

  onBlur() {
    this.setState({ isFocused: false });
  }

  render() {
    return (
      <TextInput
        {...this.props}
        // style={this.state.isFocused ? { backgroundColor: 'red' } : { backgroundColor: 'green' }}
        style={{ backgroundColor: '#aaa' }} // <<<<<<<<<<<<<<  If i delete this line then it works, just no style override
      />
    );
  }
}

And I'm trying to use it like so:

      <FocusTextInput
        ref="digit0"
        isFocused="false"
        onChangeText={this.handleDigitChanged.bind(this, 0)}
        style={styles.digitFramedControlDigit}
        maxLength={1}
        returnKeyType="next"
        selectTextOnFocus
        selectionColor="#ffffff00"
      />

So i'm able to pass those properties to the child (TextInput), how can i override the style though?

Also, i'm not sure that this is the right approach as if I want to call any of hte methods exposed by InputText on my FocusTextInput, I have to declare those methods and forward the method call. That seems silly.

Any help appreciated.

Upvotes: 0

Views: 182

Answers (2)

Samuli Hakoniemi
Samuli Hakoniemi

Reputation: 19059

The most recommended way is to use an array syntax to override from parent:

In child (FocusTextInput), apply: style={[{ backgroundColor: '#aaa' }, this.props.style]}

It's read from left to right. So backgroundColor is by default #aaa. And if this.props.style has new definition for it, then it'll override the previous one(s).

Upvotes: 1

Cory Baker
Cory Baker

Reputation: 167

You could try adding !important to you styling. See below.

 style={{ backgroundColor: '#aaa !important' }}

Upvotes: 1

Related Questions