React's context feature可用于这样的事情。实际上,react-redux
用于将商店从Provider
转换为connect
函数。
处理上下文时,通常最好与react-redux
类似,使用提供程序组件添加它,并使用higher-order component (HOC)来访问它。
提供者:
import React from 'react';
import propTypes from 'prop-types';
class FunctionProvider extends React.Component {
getChildContext() {
return {
fnc: this.props.fnc
};
}
render() {
return React.Children.only(this.props.children);
}
}
FunctionProvider.childContextTypes = {
fnc: propTypes.func
};
HOC:
import React from 'react';
import propTypes from 'prop-types';
function withFnc(WrappedComponent) {
class WithFnc extend React.Component {
render() {
return < WrappedComponent fnc={this.context.fnc} {...props} />
}
WithFnc.contextTypes = = {
fnc: propTypes.func
};
return WithFnc
}
添加FncProvider
:
function fnc (param) {
alert(param);
}
ReactDOM.render(
<Provider store={store}>
<FncProvider fnc={fnc}>
<App />
</FncProvider>
</Provider>,
document.getElementById('root')
);
裹组件:
import React from 'react';
class MyComponent extends React.Component {
render() {
return <button onClick={() => this.props.fnc('test')}>Click Me!</button>
}
}
export connect(mapStateToProps)(withFnc(MyComponent)
这可能有点过分,但如果你只需要将它传递一层或两层以及一些组件。有时props
是一个完美的解决方案。
如果您特别想使用redux来解决这个问题,您可以创建一个中间件,在特定操作上调用fnc
(我将使用ES6语法,因为它的方式更干净,但让我知道是否需要它是浏览器兼容的,我会补充说太):
const fncMiddleware = (fnc) => (store) => (next) => (action) => {
if (action.type === 'CALL_FNC') {
fnc(action.param);
}
return next(action);
}
的包括中间件,当您创建存储:
function fnc (param) {
alert(param);
}
var store = createStore(reducer, applyMiddleware(fncMiddleware(fnc)));
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
现在你可以从像任何你连接的部件派遣像{ type: 'CALL_FNC', param='test' }
行动其他活动ñ。
高阶组件[链接](https://reactjs.org/docs/higher-order-components.html)可能会帮助你。 – mersocarlin