假设我有一个组件树,如下所示
<App>
</Header>
<Content>
<SelectableGroup>
...items
</SelectableGroup>
</Content>
<Footer />
</App>
Where SelectableGroup
能够通过鼠标选择/取消选择其包含的项目。我将当前选择(选定项目的数组)存储在 redux 存储中,以便我的应用程序中的所有组件都可以读取它。
The Content
组件设置了一个ref
to the 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);
我可以很容易地想象通过这个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')
);
<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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)