如何在另一个组件呈现后呈现一个React Native组件?

时间:2017-11-29 07:43:09

标签: reactjs react-native

假设我有2个组件AB。我想渲染组件A,然后渲染组件B。为了使其更加明显,我还想在AB的渲染之间设置一些延迟(比如说2秒)。什么是最好的方法来解决这个问题?我想我应该以某种方式触发B componentDidMount Amysqli::query(): Empty query in line 83 的渲染,但我真的不知道如何触发。

谢谢:)

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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

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