【问题标题】:Passing method to child Component将方法传递给子组件
【发布时间】:2016-11-22 00:49:28
【问题描述】:

我的 React 应用有几个类似的自定义按钮,它们执行不同的任务。所有按钮的 UI 都相似,不同的是每个按钮必须触发的操作和标题。

包含按钮的父组件的工作代码(类似于)如下:

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

    action1(){
       //... do stuff...
    }

    action2(){
       //... do stuff...
    }

    render(){

        return(
            <div className="table-row">

                <div className="table-cell">
                    <div className="button" 
                        onClick={this.action1.bind(this)}>{"button1"}
                    </div>
                </div>

                <div className="table-cell">
                     <div className="button" 
                          onClick={this.action2.bind(this)}>{"button2"}
                     </div>
                </div> 
            </div>
        );
    }
}

是否可以像传递变量值一样将方法传递给子组件?我想把它变成这样的东西:

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

    action1(){
       //... do stuff...
    }

    action2(){
       //... do stuff...
    }

    render(){

        return(
            <div className="table-row">

                <div className="table-cell">
                    <CustomButton action={this.action1.bind(this)} title={"button1"}/>
                </div>

                <div className="table-cell">
                     <CustomButton action={this.action2.bind(this)} title={"button2"}/>
                </div> 
            </div>
        );
    }
}

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

    render() {
        return (
            <div className="table-cell"><div className="button" 
                onClick= {this.props.action}>{this.props.title}
            </div>
        );
    }
}

处理这种情况的正确方法及其背后的理论是什么?

我将 React 与 Meteor 一起使用,以防万一。

【问题讨论】:

  • 是的,它就是这样工作的。你说的设计缺陷是什么?
  • 该设计很好地实现了,因为它遵循 OOP。
  • 我刚刚测试了代码,它确实有效。这是一个幸运的巧合。我在 Stackoverflow 上编写了代码,考虑到这将很好地证明我的意图,并且实际的解决方案会更复杂。从来没有想过它会按原样工作!猜猜它展示了 React 和 JS 的直观性。在寻找参考之前,这可能是对自己进行测试的一个教训。无论如何,感谢您的快速回答。

标签: javascript reactjs components dom-events


【解决方案1】:

您可以将道具传递给组件。传递的道具可以有任何数据类型的 javascript。

在您的情况下,您希望传递一个具有函数作为值的动作道具。然后您访问组件中的动作道具并使用它。

简而言之,它背后没有理论。你在做什么是正确的。这就是 react 处理将数据传递给其他组件的方式。请注意,这不是将数据传递给子组件的唯一方法。

【讨论】:

  • 这是正确的,代码正在运行。谢谢@FurkanO
猜你喜欢
  • 2019-11-11
  • 2019-07-13
  • 2020-09-17
  • 1970-01-01
  • 2017-01-07
  • 2020-09-16
  • 1970-01-01
  • 2017-12-02
相关资源
最近更新 更多