假设我有 2 个组件A和B. 我想渲染组件A,然后渲染组件B。为了让更多的明显,我也想设置一些延迟(比方说2秒)的渲染之间A和B。解决这个问题的最佳方法是什么?我想我应该以某种方式引发的渲染B中componentDidMount的A,但我真的不知道该怎么做触发。
谢谢 :)
假设我有 2 个组件A和B. 我想渲染组件A,然后渲染组件B。为了让更多的明显,我也想设置一些延迟(比方说2秒)的渲染之间A和B。解决这个问题的最佳方法是什么?我想我应该以某种方式引发的渲染B中componentDidMount的A,但我真的不知道该怎么做触发。
谢谢 :)
您的问题非常模糊,并且对多种实施持开放态度。这是我的看法:
export default class App extends Component {
constructor() {
super()
this.state = { displayComponentB: false }
this.displayComponentB = this.displayComponentB.bind(this)
}
displayComponentB() {
setTimeout(() => {
this.setState({ displayComponentB: true })
}, 2000) // delay
}
render() {
return (
<View style={styles.container}>
<ComponentA onComponentDidMount={this.displayComponentB}/>
{
this.state.displayComponentB &&
<ComponentB />
}
</View>
);
}
}
export class ComponentA extends Component {
componentDidMount() {
this.props.onComponentDidMount && this.props.onComponentDidMount()
}
render() {
return (
<View style={[styles.component, styles.componentA]}>
<Text style={styles.text}>Component A</Text>
</View>
);
}
}
完整代码和现场演示:https : //snack.expo.io/SkIOLJ3eM
在 componentDidMount 中使用 setTimeout。
这是一个样本
constructor(props){
super(props);
this.state={
isBVisible:false
};
}
componentDidMount(){
setTimeout(() => {
this.setState({isBVisible:true});
}, 2000);
}
render(){
return(<View>
<View style={{width:100,height:100,backgroundColor:"red"}}/>
{this.state.isBVisible ? <View style={{width:100,height:100,backgroundColor:"green"}}/>:null}
</View>)
}