2016-09-29 56 views
1

我有以下組成部分:添加樣式是進口零部件

HelloWorld.js

class HelloWorld extends Component { 
    render() { 
    return (
     <Text style={styles.text}>Hello World!</Text> 
    ); 
    } 
} 

我它導入到另一個文件像這樣:

SignIn.js

class SignIn extends Component { 
    render() { 
    return (
     <HelloWorld style={styles.signInText} /> 
    ); 
    } 
} 

正如您在SignIn.js中看到的那樣,我想將styles.signInText包括到組件中,但是由於我已經將style屬性設置爲HelloWorld.js,因此無法完成此操作。

我知道我可以將樣式導入SignIn.js,並且像這樣:<HelloWorld style={[styles.text, styles.signInText]} />但是,這是一個混亂的解決方案。

如何允許在我的HelloWorld組件中使用其他樣式?謝謝。

+0

你可以將兩種樣式都傳遞到那裏然後做這個.props.styles – Kafo

回答

0

您需要將樣式作爲道具傳遞給HelloWorld組件。

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

如果你想的Textstyle財產的價值在裏面HelloWorld當地styles的組合和傳遞給HelloWorldstyle財產的價值,你可以做秒。

class HelloWorld extends Component { 
    render() { 
    return (
     <Text style={{...styles, ...this.props.style}}>Hello World!</Text> 
    ); 
    } 
} 

這將解構當地styles變量到一個新的對象,同時也解構的HelloWorldstyle財產,到同一個對象。最終結果傳遞給Textstyle屬性。請記住,如果傳遞給HelloWorldstyle屬性具有屬性鍵,該屬性鍵也存在於本地styles對象文字中,則它將覆蓋本地對象文字中的一個。

+0

我不明白你的意思,我把'HelloWorld'組件中的樣式改成'{{... styles,... this。 props.style}}',但是這樣做不包括'styles.text'的樣式。我錯過了你在說什麼嗎? –

+0

根據你的代碼示例,它應該,儘管我沒有看到'styles.text'在哪裏被首先定義。你確定它是由你實際使用它的時間來定義的嗎? –