简体   繁体   English

ReactJS:无状态组件中的有状态子级

[英]ReactJS: Stateful children in stateless component

在无状态组件中包含有状态的子项是否会使该组件不再无状态?

Short answer 简短答案

No, it doesn't. 不,不是。


The life-cycle methods that are associated with a component that has state should work independently of where they are in the component hierarchy, otherwise things would break in unpredictable ways. 与具有状态的组件关联的生命周期方法应独立于其在组件层次结构中的位置而工作,否则,事情将以不可预测的方式中断。

Here's proof that stateless components have a backing instance of a class, so they can use ref s and life-cycle methods: 这证明无状态组件具有类的支持实例,因此它们可以使用ref和生命周期方法:

 class StatefulComponent extends React.Component { componentDidMount() { this.wrapper.classList.add("highlight"); } render() { return ( <div ref={ref => this.wrapper = ref}> Stateful (red outline due to class being added) {this.props.children} </div> ); } } const StatelessComponent = props => ( <div> Stateless (black outline) {props.children} </div> ); ReactDOM.render( <StatefulComponent> <StatelessComponent> <StatefulComponent /> </StatelessComponent> </StatefulComponent>, document.getElementById("app")); 
 div { padding: 20px; outline: 1px solid; } .highlight { outline-color: red; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="app"></div> 

State is a property privately managed by a component and hence a component being stateless is decided by its own self and not by its parents or children. 国家是由组成部分私人管理的财产,因此, 组成无国籍状态是由其自己而不是其父母或子女决定的。

No lifecycle hooks are available within the stateless component whereas they continue to work as desired in their children. 无状态组件中没有可用的生命周期挂钩,而它们仍可继续在其子代中正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM