javascript - 从子组件调用父组件的方法 - React Native

标签 javascript mobile react-native

我正在开发我的第一个应用程序,并且仍在学习流程。 所以假设我有一个组件叫做:

持有方法 HelloWorld() 的父级,如下例所示:

import React, { Component } from 'react';

class Parent extends Component {
    Helloworld() {
        console.log('Hello world');
    }

    render () {
        return (
            <View>{this.props.children}</View>
        )
    }
}

module.exports = Parent;

然后我想将它导入另一个组件并使用它的方法,那么我该怎么做呢? 我会写另一个简短的例子来说明我将如何实现它。

import React, { Component } from 'react';

import { Parent } from 'path to parent'; 
//or
const Parent = require('path to parent');
//which of these is better?

class Home extends Component {
    Helloworld() {
        console.log('Hello world');
    }

    render () {
        return (
            <Parent>
                // this is what i need
                <Button onClick={parent.Helloword()}>Some Button</Button>
            </Parent>
        )
    }
}

module.exports = Home;

在此先感谢您的帮助。

最佳答案

通常你应该通过 Prop 将信息从 parent 传递给 child 。

parent.jsx:

import Child from './child';

class Parent extends Component {
    constructor(props) {
        super(props);

        this.helloWorld = this.helloWorld.bind(this);
    }

    helloWorld() {
        console.log('Hello world!');
    }

    render() {
        return (
            <View><Child method={this.helloWorld} /></View>
        );
    }
}

child.jsx:

class Child extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <Button onClick={this.props.method} />
        );
    }
}

编辑:关于 importrequire 之间的偏好,我相信这是一个品味问题,但我认为 import 更干净。

关于javascript - 从子组件调用父组件的方法 - React Native,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38650992/

相关文章:

javascript - history.js 和标题重定向

javascript - 使用按钮 D3 隐藏/显示网格线

javascript - 如何在单击提交按钮之前隐藏标签?

javascript - 如何在 JavaScript 中通过滑动来跟踪链接?

android - 在 react-native 中包含 react-vr

ios - react native 应用程序-获取错误app.js无法读取未定义的属性'文件名'

javascript - 如何克隆具有新id的元素?

javascript - onClick 不适用于移动设备(触摸)

css - 加载大图片时的临时背景图片?

javascript - react native : Inline image with text