2015-10-07 110 views
1

我正在使用react-router,並且我需要將props傳遞給處理程序Comments組件(請參閱下面的代碼)。通常是solved by creating a wrapper componentreact-router:將道具傳遞給es6處理程序組件

但是Comments已經是AbstractComments的es6包裝,所以我不想再創建一個包裝。所以,我這樣做是在未來的方式:

問題/疑問:看看請Comments#onChange方法

評論組件

// Where AbstractComment extends React.Component 
class Comments extends AbstractComments { 

    constructor(props) { 
     //Pass my custom props to component 
     super(_.assign(props, { 
      chatName: '....', 
      title: '...', 
      comments: '.....' 
     })); 
    } 

    _onChange() { 
     //PROBLEM: after setState Comments component get rendered 
     //without my custom props: (chatName, title, comments) 
     //QUESTION: how to re-render it with the same properties? 
     this.setState(someNewState); 
    } 

} 

如何Comments被渲染react-router:

var Index = React.createClass({ 
    render: function() { 
    return (
     <div> 
      <header>Some header</header> 
      <RouteHandler /> 
     </div> 
    ); 
    } 
}); 

var routes = (
    <Route path="/" handler={Index}> 
    <Route path="comments" handler={Comments}/> 
    <DefaultRoute handler={Dashboard}/> 
    </Route> 
); 

ReactRouter.run(routes, function (Handler) { 
    React.render(<Handler/>, document.body); 
}); 
+0

非常簡單的解決方案 - 做'Comments.defaultProps = {...}'而不是將它們分配給構造函數 –

回答

0

將默認值分配給defaultProps中的道具,如下所示。

class Comments extends AbstractComments { 

    constructor(props) { 
    //Pass my custom props to component 
    super(_.assign(props, { 
     chatName: '....', 
     title: '...', 
     comments: '.....' 
    })); 
    } 

    _onChange() { 
    //PROBLEM: after setState Comments component get rendered 
    //without my custom props: (chatName, title, comments) 
    //QUESTION: how to re-render it with the same properties? 
    this.setState(someNewState); 
    } 

} 
Comments.defaultProps = {chatName: '....', 
     title: '...', 
     comments: '.....'}; 

export default Comments ;