简体   繁体   中英

Adding styles to an imported component

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.

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.

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>
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM