react-router:将props传递给es6处理程序组件

时间:2015-10-07 08:05:18

标签: javascript reactjs react-router

我正在使用react-router,我需要将props传递给处理程序Comments组件(请查看下面的代码)。通常是solved by creating a wrapper component

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

}

react-router如何呈现Comments

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

1 个答案:

答案 0 :(得分:0)

将默认值分配给defaultProps中的props,如下所示。

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 ;