如何从子组件向app.jsx发送或更新数据作为state或prop

时间:2017-05-03 11:23:26

标签: reactjs components

我是反应中的新手。

我需要点击按钮

更改整个视图

为此,我需要从子组件更新父组件的状态。

就像我们作为会话变量一样。你们对它有什么想法然后请帮助我。

提前致谢。

这是我的代码:

App.jsx

class App extends React.Component {
constructor(props) {
    super(props)
}

render() {
    let RedirectTo = this.state.page;
    let RenderPage;

    switch (RedirectTo) {
        case 'component':
            RenderPage = true && <NextPage />;
            break;
        default:
            RenderPage = true && <Index />;
    }

    return (
            <div>
                {RenderPage}
            </div>
            );
}

Child.jsx

class Child extends React.Component {
constructor(props) {
    super(props);
    this.state = {redirect: 'yes'};
    this.state = {page: 'component'};
}

render() {
    if (this.state.redirect === 'yes') {
        return (
                <div>
                    { true && <App /> }
                </div>
                );
    } else {
        return (
                <div>
                    <a onClick={this.Validate} href="javascript:void(0);">
                        Click To Next
                    </a>  
                </div>
                );
    }
}

3 个答案:

答案 0 :(得分:0)

只需在父母中创建一个函数,如

function () {
// your functionality here
}

然后将父组件中的子组件调用为

<child functionProp = {this.function} />

在您的子组件中,通过

调用父项中的函数
this.props.functionProp

答案 1 :(得分:0)

首先,React组件处理父对子方式而不是子对父进程,无论你想调用什么函数都可以影响你的父对子,然后你必须将props传递给子进程,并通过父进行调用以便影响你的父母和孩子,

您想要尝试实现的是错误的方式您必须在您的应用程序中引入路由器,该路由器可以将一个页面路由到另一个页面,您需要检查React-Router,以便基本上将一个组件导航到另一个组件我们可以轻松地使用react-router,React-Router

答案 2 :(得分:0)

在父级中,您可以将props函数传递给子级:

<child someFunction={this.handleFunction} />

在父母的handleFunction方法中,你可以做任何你想做的事。

handleFunction(value) {
    //do something
}

在孩子中,您可以将someFunction称为:

this.props.someFunction(value)

通过这种方式,您可以通过孩子与父母沟通。