如何在另一个组件渲染后渲染一个 React Native 组件?

IT技术 reactjs react-native
2021-05-28 02:18:15

假设我有 2 个组件AB. 我想渲染组件A,然后渲染组件B为了让更多的明显,我也想设置一些延迟(比方说2秒)的渲染之间AB解决这个问题的最佳方法是什么?我想我应该以某种方式引发的渲染BcomponentDidMountA,但我真的不知道该怎么做触发。

谢谢 :)

2个回答

您的问题非常模糊,并且对多种实施持开放态度。这是我的看法:

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>)
}