【问题标题】:How to invoke a function in parent component from deeply nested child component using redux如何使用 redux 从深度嵌套的子组件调用父组件中的函数
【发布时间】:2016-05-07 17:31:17
【问题描述】:
class Parent extends React.Component{
    constructor(props){
        super(props);
        this.clicked = this.clicked.bind(this);
    }

    getChildrenValues(){
        console.log("Children values");
    }

    render(){
        return <div>
            Parent 

            <Component1>

                <Component2>
                    <Child />   

                </Component2>

            </Component1>

        </div>
    }
}


class Child extends React.Component{
    constructor(props){
        super(props);
        this.clicked = this.clicked.bind(this);
    }

    clicked(){
        this.props.dispatch({type: "InvokeParent"});
    }

    render(){
        return <div>
            <button onClick = {this.clicked}>Click Here</button>
        </div>
    }
}

如何从“Child”组件调用 getChildrenValues 函数。我正在尝试从父组件获取所有子值并提交,但我不知道如何在 redux 中触发该功能。在不断变化的情况下,我曾经做 addChangeListener 并触发该功能。

【问题讨论】:

  • 你希望这个父函数在你的真实情况下做什么?它会影响你的全球状态吗?在您当前的示例代码中,我会说根本不使用 redux,只需将函数作为道具传递并在点击时调用道具
  • 通过调用该函数,我将调用子常用方法,如 getValue - 它返回子组件的状态并提交数据。

标签: reactjs redux react-redux


【解决方案1】:

仅根据您的示例,我会说这种情况根本不会涉及 redux。 Redux 是一个管理全局状态的工具。这个例子中没有任何东西是接触状态。

为了让这个示例代码正常工作,将您的方法作为道具传递并在点击时调用它。如果取决于子组件的嵌套程度,这可能会很混乱。

class Parent extends React.Component{
    constructor(props){
        super(props);
        this.clicked = this.clicked.bind(this);
    }

    getChildrenValues(){
        console.log("Children values");
    }

    render(){
        return <div>
            Parent 

            <Component1>

                <Component2>
                    <Child invokeParent={this.getChildrenValues} />   

                </Component2>

            </Component1>

        </div>
    }
}


class Child extends React.Component{
    constructor(props){
        super(props);
        this.clicked = this.clicked.bind(this);
    }

    clicked(){
        this.props.dispatch({type: "InvokeParent"});
    }

    render(){
        return <div>
            <button onClick = {this.props.invokeParent}>Click Here</button>
        </div>
    }
}

【讨论】:

  • 是的,正如你所说,代码会变得混乱,这就是为什么我试图从子组件调度一个动作并获取主父级的所有子级值并提交值。
猜你喜欢
  • 1970-01-01
  • 2017-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多