gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:50:36 26 4
gpt4 key购买 nike

我正在使用react-router,我需要将 Prop 传递给处理程序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);
});

最佳答案

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

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 ;

关于javascript - React-router:将 props 传递给 es6 处理程序组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32986904/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com