简体   繁体   中英

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:

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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