首页 > 解决方案 > 从父组件触发子组件内部的函数

问题描述

如何以与抽屉导航相同的样式从父组件触发子组件内部的函数。

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

我该怎么做?

标签: reactjsreact-native

解决方案


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

我将尝试通过 2 个示例来澄清一下。

1)从孩子触发:

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

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)。您可以检查属性更改,然后在子组件中执行您需要执行的操作。

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(
      {/* ... */}
    )
  }
}

推荐阅读