从父级触发子组件内的函数

从父级触发子组件内的函数

本文介绍了从父级触发子组件内的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从父组件触发子组件内部的函数,以与抽屉导航相同的样式执行此操作.

How can I trigger a function that is inside the child component from the parent component doing it in the same style as drawer navigation.

他们这样做:this.props.navigation.toggleDrawer(); 来自父

我该怎么做?

推荐答案

如果我正确理解你的问题,我认为你有点混淆了.您展示的示例是从子组件触发父组件功能的示例.

If I understood your question correctly, I think you mixed up thing a bit. The example you are showing is an example for triggering a parent component's function from child.

我会试着用 2 个例子来澄清一下.

I'll try to clear things up a bit with 2 examples.

1) 来自孩子的触发:

要从子组件触发父组件的函数,您只需将该函数作为属性传递给子组件,并在需要时运行它.

To trigger a function of a parent component from a child you can just pass the function as a property to the child component and run it when you need it.

class Parent extends React.Component {
  someFunction = (text) => {
    console.log('Message from child: ', text);
  }
  render () {
    return(
      <Child someProperty={this.someFunction} />
    )
  }
}

class Child extends React.Component {
  _onPress = () => {
    // check if the property is defined and not null
    if(this.props.someProperty) {
      // run the function that is passed from the parent
      this.props.someProperty();
    }
  }
  render() {
    return(
      <Button onPress={this._onPress} title="Click Me"/>
    )
  }
}

2) 来自父级的触发:

要从父组件触发子组件上的函数,您可以传递一个属性,该属性会在父组件上发生某些操作时发生变化.这将触发重新渲染(在大多数情况下,有关更多信息,请查看 shouldComponentUpdate) 在子组件中.您可以检查属性更改,然后在子组件中执行您需要执行的操作.

To trigger a function on a child component from parent, you can pass a property that changes when some action happens on the parent component. This will trigger a re-render (in most cases, for more info please take a look at shouldComponentUpdate) in child component. You can check the property changes and then do what you need to do in child component.

class Parent extends React.Component {
  state = {
    someParameter: 'someInitialValue',
  }
  someFunction = (text) => {
    this.setState({ someParameter: 'someValue' });
  }
  render () {
    return(
      <Child someProperty={this.state.someParameter} />
    )
  }
}

class Child extends React.Component {
  someFunction = (text) => {
    console.log('Message from parent: ', text);
  }
  componentDidUpdate(prevProps, prevState, snapshot) {
    // Check if the suplied props is changed
    if(prevProps.someProperty !== this.props.someProperty) {
      // run the function with the suplied new property
      this.someFunction(this.props.someProperty);
    }
  }
  render() {
    return(
      {/* ... */}
    )
  }
}

这篇关于从父级触发子组件内的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:02