在无状态组件中拥有有状态子组件是否会使组件不再无状态?
最佳答案
简短回答
不,事实并非如此。
与具有状态的组件关联的生命周期方法应该独立于它们在组件层次结构中的位置工作,否则事情会以不可预测的方式中断。
这里证明无状态组件具有类的支持实例,因此它们可以使用 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>
关于javascript - ReactJS:无状态组件中的有状态子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47911965/