在我的组件类中,我有 this.props
,其中包含 history
对象,其中包含 transitionTo
函数。
render() {
console.log(this.props)
return (
<div>
<button onClick={actions.myAction}>My button</button>
</div>
这里我的按钮正在调用myAction
,它在完成后想要路由到其他位置。我想在我的 action
中访问这个 transitionTo
函数并执行类似 router.transitionTo("/page1")
为此,我应该获取包含 transitionTo
函数的 history
对象。那么如何将 this.props.history
对象传递给操作。当我执行 onClick={actions.myAction(this.props.history)}
时,我的按钮没有被渲染..
任何帮助
最佳答案
上面的答案是正确的,但在迁移到 "Stateless Components" 时就会崩溃。这很快就会崩溃。我的建议是使用高阶函数来处理防止默认单击操作和提供正确参数的处理。如果您已经在使用 ES2015(例如通过 Babel),这可能很简单:
const preventDefault = (fn, ...args) => (e) => {
e.preventDefault();
fn(...args);
};
然后在你的组件中像这样调用:
const Item = ({
item,
openItem
}) => (
<div>
<h1>{item.title}</h1>
<a href="#" onClick={preventDefault(openItem, item)}>Open Item</a> // on click will call `openItem(item)`.
</div>
)
关于reactjs - React redux 将 this.props 传递给组件中的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35149207/