2017-10-20 54 views
0

這是我試圖做的一個例子。我想傳遞MyComponent類中的道具,而不使用<MyComponent hello={'Hello World'}/>,因爲我將MyComponent傳遞給其他一些庫。reactjs,如何通過課堂級別的道具

import React, { Component } from 'react'; 

class MyComponent extends Component { 
    render() { 
    const { hello } = this.props; 
    return (
     <div>{hello}</div> 
    ); 
    } 
} 

// this line is wrong 
MyComponent.props = { 
    hello: 'Hello World!' 
} 

<MyComponent /> 

react-redux如何連接以添加this.props.state並將任何其他函數映射到組件的道具?我想將自定義對象注入組件。

+0

想想你在問什麼。你想傳遞道具,而不通過道具。否:這不是你如何使用React的方法。在你的例子中,只需說'let props = {...}',然後使用''因爲這很好:沒有理由不想做這個事實上是有道理的從編程的角度來看。 –

回答

1

你需要創建一個Higher Order Component

function withMyObject(WrappedComponent,helloText) { 
    return class extends React.Component { 

    render() { 
     return <WrappedComponent {...this.props} hello={helloText} />; 
    } 
    }; 
} 

用法:

UpdatedComponent = withMyObject(ComponentToBeWrapped,"Hello"); 
2

您可以設置默認的道具。我認爲這是一個很好的做法。

import React, { Component } from 'react'; 

class MyComponent extends Component { 
    render() { 
    const { hello } = this.props; 
    return (
     <div>{hello}</div> 
    ); 
    }headerProp: "Header from props...", 
    contentProp:"Content from props..." 
} 

MyComponent.defaultProps = { 
    hello: 'Hello World!' 
} 

<MyComponent />