我是个新手,我想知道把处理程序从顶层元素传递到深度嵌套子元素的正确方式是什么。我发现自己通过中间子道具移动处理程序,但如果感觉像是流水线,这不是正确的解决方案。我想有更好的方法来做到这点。感谢您的指点
发布于 2016-08-12 01:57:30
可以考虑的一件事是使用redux和react-redux的connect将深度嵌套子组件“连接”到存储区。
/* your deeply nested child */
import { connect } from 'react-redux';
import { actionCreator1, actionCreator2 } from './path/to/actionCreators';
@connect(
(state) => ({
prop1: state.path.to.prop1,
prop2: state.path.to.prop2
}),
(dispatch) => ({
onBtnClick: e => dispatch(actionCreator1()),
onSomethingChange: e => dispatch(actionCreator2(e.target.value))
})
)
class MyComponent extends React.Component {
render() {
return (
<div>
<input
type="text"
value={this.props.prop1}
onChange={this.props.onSomethingChange}
/>
<button onClick={this.props.onBtnClick}>submit</button>
</div>
);
}
}在你的根组件中:
import store from './path/to/reduxStore';
import { Provider } from 'react-redux';
class RootComponent extends React.Component {
render() {
<Provider store={store}>
<YourParentComponent />
</Provider>
}
}更详细的例子在这里Usage with React
https://stackoverflow.com/questions/38901558
复制相似问题