首页 文章

从React Native中的父组件调用子函数

提问于
浏览
20

我正在开发我的第一个React Native应用程序 . 我想要实现的是从父组件执行子函数,这是这样的情况:

Child

export default class Child extends Component {
  ...
  myfunct: function() {
    console.log('Managed!');
  }
  ...
  render(){
    return(
      <Listview
      ...
      />
    );
  }
}

Parent

export default class Parent extends Component {
  ...
  execChildFunct: function() {
    ...
    //launch child function "myfunct"
    ...
    //do other stuff
  }

  render(){
    return(
      <View>
        <Button onPress={this.execChildFunct} />
        <Child {...this.props} />
      </View>);
  }
}

在这个例子中,当我按下父类中的按钮时,我想记录 'Managed!' . 它怎么可行?

4 回答

  • 20

    您可以为子组件添加引用:

    <Child ref='child' {...this.props} />
    

    然后像这样调用孩子的方法:

    <Button onPress={this.refs.child.myfunc} />
    
  • 2

    Nader Dabit的答案已经过时,因为在ref属性has been deprecated中使用了字符串文字 . 这就是我们2017年9月的表现:

    <Child ref={child => {this.child = child}} {...this.props} />
    <Button onPress={this.child.myfunc} />
    

    相同的功能,但我们不是使用String来引用组件,而是将其存储在全局变量中 .

  • 3

    我认为你误解了组件结构 .

    假设您的孩子是为您的其他组件生成按钮的组件 . 在此层次结构中,您的孩子必须通知其父母已被按下 .

    孩子----->父母

    export default class Child extends Component {
    
         return(
        <Button onPress={this.props.onPress } />
         );
      }
    

    在父组件中,使用子组件为您生成一个按钮 . 通过这种方式,您可以将子组件作为独立按钮使用任何其他组件 .

    export default class Parent extends Component {
    constructor(props) {
        super(props);
        this.execChildFunct=this.execChildFunct.bind(this)
      }
    
      execChildFunct: function() {
      console.log('Managed!');
      }
      return (
       <Child onPress = {this.execChildFunct}></Child>
      )
    
    }
    
  • 15

    it is in react. i hope it may help you.

    class Child extends React.Component {
      componentDidMount() {
        this.props.onRef(this)
      }
      componentWillUnmount() {
        this.props.onRef(null)
      }
      method() {
        console.log('do stuff')
      }
      render() {
        return <h1>Hello World!</h1>
      }
    }
    

    class EnhancedChild extends React.Component {
            render() {
            return <Child {...this.props} />
          }
        }
    
    class Parent extends React.Component {
      onClick = () => {
        this.child.method() // do stuff
      };
      render() {
        return (
          <div>
            <EnhancedChild onRef={ref => (this.child = ref)} />
            <button onClick={this.onClick}>Child.method()</button>
          </div>
        );
      }
    }
    
    ReactDOM.render(<Parent />, document.getElementById('root'))
    

    Original Solution:

    https://jsfiddle.net/frenzzy/z9c46qtv/

    https://github.com/kriasoft/react-starter-kit/issues/909

相关问题