export class Child extends React.Component{
unmount() {
const node = ReactDOM.getDOMNode(this);
ReactDOM.unmountComponentAtNode(node );
}
render() {
return <button onClick={this.unmount.bind(this)}>Unmount</button>
}
}对于上面的示例组件,是否可以使用unmountComponentAtNode在单击时将其卸载
发布于 2018-05-28 16:13:53
React应用程序总是一个组件组合,或者换句话说--组件树。这意味着每个组件都有父组件,父组件呈现它,它只是根组件的虚假陈述,我们通常将其命名为应用程序,但我们不在该问题中讨论它。最重要的是,我们可以说一个需要卸载的组件总是有一个父组件。
正如我们在第一段中所做的假设,卸载React组件的正确方法是将其从父组件的render方法中删除。它可以通过很多方式来完成,最简单的就是一个有条件的组件渲染,比如:
class IAmParentComponent extends React.Component {
render() {
return (<div>{this.state.show && <YourChildComponentToUnmount/>}</div>)
}
}上面的示例显示了IAmParentComponent作为容器组件,它保存了一个状态,如果this.state.show为true,则YourChildComponentToUnmount将呈现,在状态从true更改为false后将卸载。
用回调返回到你的代码中,回调应该由道具发送到组件中,父组件应该做与从渲染树中移除组件相关的状态更改,具体是什么将启动组件的卸载阶段,最后组件将从UI中移除。
总而言之,组件卸载应由其上的组件负责,组件不应自行卸载。
发布于 2018-05-28 15:15:48
这不是反应的方式。卸载元素的最好方法是告诉父元素从父元素的渲染子元素中删除该子元素。
看看这个例子。这里有CardContainer类,CardItem class.The CardItem item类有一个delete self按钮。此方法将事件发送到父容器以从呈现的子容器中移除自身。
const carddata = [
{key:1 ,name: 'Card A',visible:true},
{key:2 ,name: 'Card B',visible:true}
];
class CardItem extends React.Component {
constructor(props){
super(props)
this.handleClick=this.handleClick.bind(this);
}
componentWillUnmount(){
console.log('unmount')
}
handleClick(){
this.props.destroy(this.props.id)
}
render(){
return(<div>
Card
<button onClick={this.handleClick} >delete</button>
</div>)
}
}
class CardContainer extends React.Component {
constructor(props){
super(props)
this.state = {data: carddata};
this.destroy = this.destroy.bind(this);
}
destroy(elementKey){
console.log(elementKey)
debugger
let result = this.state.data.filter(item=> item.key !==elementKey);
this.setState({data: result});
}
render(){
return (<div>
Card Container
{this.state.data.map((card,index) => {
return <CardItem key={card.key} id={card.key} name={card.name} destroy={this.destroy}/>
})
}
</div>)
}
}https://stackoverflow.com/questions/50557662
复制相似问题