Reputation: 6944
I have the following component:
HelloWorld.js
class HelloWorld extends Component {
render() {
return (
<Text style={styles.text}>Hello World!</Text>
);
}
}
I import it in another file like so:
SignIn.js
class SignIn extends Component {
render() {
return (
<HelloWorld style={styles.signInText} />
);
}
}
As you can see in SignIn.js, I want to include styles.signInText
to the component, however this cannot be done as I have already set the style attribute to in HelloWorld.js.
I know I could import the styles into SignIn.js and have it like so: <HelloWorld style={[styles.text, styles.signInText]} />
however this is a messy solution.
How can I allow the use of additional styles in my HelloWorld component? Thanks.
Upvotes: 1
Views: 73
Reputation: 7126
If you want the value of the style
property of Text
to be a combination of the local styles
inside HelloWorld
and the value passed to the style
property of HelloWorld
, you could do this.
class HelloWorld extends Component {
render() {
return (
<Text style={{...styles, ...this.props.style}}>Hello World!</Text>
);
}
}
This will deconstruct the local styles
variable into a new object while also deconstructing the style
property of HelloWorld
, into the same object. The final result is passed to the style
property of Text
. Keep in mind though that if the style
property passed to HelloWorld
has a property key that also exists in the local styles
object literal, it will override the one in the local styles
object literal.
Upvotes: 2
Reputation: 341
You need to pass the styles as a prop to the HelloWorld
component.
SignIn.js
class SignIn extends Component {
render() {
return (
<HelloWorld signInText={styles.signInText} />
);
}
}
HelloWorld.js
class HelloWorld extends Component {
render() {
const { signInText } = this.props;
return (
<Text style={[styles.text, signInText]}>Hello World!</Text>
);
}
}
Upvotes: 0