Javascript React Native-如何从子组件调用函数?
我正在尝试创建一个计时器组件,当从父组件调用其启动函数时,它应该启动: 计时器:Javascript React Native-如何从子组件调用函数?,javascript,react-native,Javascript,React Native,我正在尝试创建一个计时器组件,当从父组件调用其启动函数时,它应该启动: 计时器: class Timer extends Component { start = () => { //starts the timer here } } 家长: class Parent extends Component { render () { <Timer /> // how do I call the start function from th
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?
}
}
类父级扩展组件{
渲染(){
//如何从父组件调用start函数?
}
}
您应该从
触发更改道具,然后启动组件willreceiveprops
中的计时器。小例子
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}/>
}
}
通过设置对子函数的引用,可以从父函数调用子函数
//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();
}
}
//子对象
类计时器扩展组件{
开始=()=>{
//在这里启动计时器
}
}
//母公司
类父级扩展组件{
rende(){
this.Timer=component}/>
}
someParentFunction(){
this.Timer.start();
}
}
因此,以下做法非常糟糕,通常情况下,如果您发现自己处于一种需要从一个孩子传递到另一个家长的情况下,则会出现更大的问题
此外,此解决方案不应逐字使用,而是让您真正了解如何将函数从子函数传递回父函数
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} />
}
}
类计时器扩展组件{
componentDidMount(){
this.props.setIt(this.start)
}
开始=()=>{
//在这里启动计时器
}
}
类父级扩展组件{
设置它=(启动触发器)=>{
startTrigger()//您现在可以访问此函数来执行所需操作
}
渲染(){
}
}
这种情况的用例是什么?您是否可以从计时器组件中调用启动
?
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} />
}
}