React Native-如何从子组件中调用函数?

时间:2018-10-25 13:18:48

标签: javascript react-native

我正在尝试制作一个Timer组件,该组件应在从父组件调用其启动函数时启动:

计时器:

class Timer extends Component {
   start = () => {
      //starts the timer here
   }
}

父母:

class Parent extends Component {
   render () {
      <Timer /> // how do I call the start function from this parent component?
   }
}

3 个答案:

答案 0 :(得分:3)

您可以通过设置对子级的引用来从父级调用子级功能。

//Child
class Timer extends Component {
    start = () => {
        //starts the timer here
    }
}

//Parent
class Parent extends Component {

    rende() {
        <Timer ref={ ( component ) => this.Timer = component }/>
    }

   someParentFunction() {
       this.Timer.start();
   }

}

答案 1 :(得分:1)

您应该从 Dim ra As Range Dim length As Integer Set ra = Range("AE:AE").Find(What:="Dell EMC Maintenance Representative", LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False) length = Len(ra) If length < 40 Then MsgBox ("Sales Rep. is missing!") GoTo BEG Else 触发更改道具,然后在<Timer>中启动计时器。小例子

componentWillReceiveProps

class Parent extends Component { //set the state to this.state={runTimerStart: false} onParentAction = () => { //call this onParentAction function when you want to start the timer this.setState({runTimerStart: true}) } render () { <Timer runStart={this.state.runTimerStart}/> } }

<Timer>

答案 2 :(得分:0)

因此,以下做法确实是不好的做法,通常,如果您发现自己需要从孩子传给父母的情况下,会有更大的问题。

此解决方案也不应逐字使用,而应为您提供一个很好的主意,即如何将功能从子级传递回父级

class Timer extends Component {
   componentDidMount() {
      this.props.setIt(this.start)
   }

   start = () => {
      //starts the timer here
   }
}

class Parent extends Component {

   setIt = (startTrigger) => {
     startTrigger() // You now have access to this function to do what you wish
   }

   render () {
      <Timer setStartTrigger={this.setIt} />
   }
}