Beh*_*nil 5 reactjs react-redux
假设我有一个组件树,如下所示
<App>
</Header>
<Content>
<SelectableGroup>
...items
</SelectableGroup>
</Content>
<Footer />
</App>
Run Code Online (Sandbox Code Playgroud)
可以SelectableGroup通过鼠标选择/取消选择其包含的项目。我将当前选择(选定项目的数组)存储在 redux 存储中,以便我的应用程序中的所有组件都可以读取它。
该Content组件已将 a 设置ref为 ,SelectableGroup这使我能够以编程方式清除选择(调用clearSelection())。像这样的东西:
class Content extends React.Component {
constructor(props) {
super(props);
this.selectableGroupRef = React.createRef();
}
clearSelection() {
this.selectableGroupRef.current.clearSelection();
}
render() {
return (
<SelectableGroup ref={this.selectableGroupRef}>
{items}
</SelectableGroup>
);
}
...
}
function mapStateToProps(state) {
...
}
function mapDispatchToProps(dispatch) {
...
}
export default connect(mapStateToProps, mapDispatchToProps)(Content);
Run Code Online (Sandbox Code Playgroud)
我很容易想象将这一点传给clearSelection()我Content的孩子们。但这是我的问题,我如何clearSelection()从兄弟组件中调用Footer?
Footer并将某种“请求调用清除选择”状态设置为 Redux 存储吗?componentDidUpdate()在回调中对此做出反应Content,然后立即调度另一个操作来重置此“请求调用清除选择”状态?您可以使用 ref 来访问 Content 组件的全部功能,如下所示
const { Component } = React;
const { render } = ReactDOM;
class App extends Component {
render() {
return (
<div>
<Content ref={instance => { this.content = instance; }} />
<Footer clear={() => this.content.clearSelection() } />
</div>
);
}
}
class Content extends Component {
clearSelection = () => {
alert('cleared!');
}
render() {
return (
<h1>Content</h1>
);
}
}
class Footer extends Component {
render() {
return (
<div>Footer <button onClick={() => this.props.clear()}>Clear</button>
</div>
);
}
}
render(
<App />,
document.getElementById('app')
);Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13549 次 |
| 最近记录: |