将数据从父类发送到子类

时间:2019-10-07 08:02:08

标签: react-native

如何将父类数据发送到子类。父班级数据每3秒更改一次。 当父类数据发生更改时,我希望每3秒将什么发送到子类,并根据数据更改其状态。

parent class

  export default class ChildPickRoute extends Component{
    ...
   onTimeChange = (Time) =>{
      this.Co_Time  = Time
    //this.Co_Time is changing every 3 seconds
    }

   render(){
  if(this.state.currentScreen == "showMap")
  {
    const {stopsData} = this.state;
    const {stopId} = this.state;
    const {stopSequence} = this.state;
    const {routeId} = this.state;
    const {pickData} =this.state

    return(
      <View style={styles.container}>
        <MapAnimateToRegion
        stopsData = {stopsData}
        stopId = {stopId}
        routeId = {routeId}
        stopSequence = {stopSequence}
        Data = {pickData}
        onRef={ref => (this.TimeparentReference = ref)}
        TimeparentReference = {this.onTimeChange.bind(this)}
        />
    <Slider
    data = {stopsData}
    StopId = {stopId} 
    StopSequance = {stopSequence}
    />
     <CoTime />
</View>
)
 }

Child class

class CoTime extends Component{
constructor(props){
  super(props);
  console.log("coming to child")
}
componentWillReceiveProps(props){
  console.log("props", props)
}
 render(){
   return(
     <View>

     </View>
   )
 }
}

1 个答案:

答案 0 :(得分:0)

您可以通过组件的道具发送值。这样...

Parent comp

export default class ChildPickRoute extends Component{
  ...
  onTimeChange = (Time) =>{
    //this.Co_Time  = Time
    this.setState({ Co_Time: Time })
    //this.Co_Time is changing every 3 seconds
  }

  render(){
    if(this.state.currentScreen == "showMap")
    {
      const {stopsData, stopId, stopSequence, routeId, pickData, Co_Time} = this.state;

      return(
        <View style={styles.container}>
          <MapAnimateToRegion
          stopsData = {stopsData}
          stopId = {stopId}
          routeId = {routeId}
          stopSequence = {stopSequence}
          Data = {pickData}
          onRef={ref => (this.TimeparentReference = ref)}
          TimeparentReference = {this.onTimeChange.bind(this)}
          />
          <Slider
          data = {stopsData}
          StopId = {stopId} 
          StopSequance = {stopSequence}
          />
          <CoTime coTimeValue={Co_Time} />
        </View>
      )
    }
}

Child comp

class CoTime extends Component{
  constructor(props){
    super(props);
    console.log("coming to child")
  }

  componentWillReceiveProps(props){
    console.log("props", props)
  }

  render(){
    const { coTimeValue } = this.props;

    return (
      <View></View>
    )
  }
}

此外,您不应再使用componentWillReceiveProps。它已被React官员掩盖为UNSAFE方法。

https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops