React.js如何将回调传递给子组件?

时间:2022-08-22 19:21:47

I would like to pass a callback to a doubly nested component, and while I am able to pass the properties effectively, I can't figure out how to bind the callback to the correct component so that it's triggered. My structure looks like this:

我想将回调传递给双嵌套组件,虽然我能够有效地传递属性,但我无法弄清楚如何将回调绑定到正确的组件以便它被触发。我的结构看起来像这样:

-OutermostComponent
    -FirstNestedComponent
        -SecondNestedComponent
            -DynamicallyGeneratedListItems

The List Items when clicked should trigger a callback which is the OutermostComponents method "onUserInput", but instead I get "Uncaught Error: Undefined is not a function". I suspect the problem is in how I am rendering the SecondNestedComponent inside the first, and passing it the callback. The code looks something like this:

单击列表项时应触发回调,即OutermostComponents方法“onUserInput”,但我得到“未捕获错误:未定义不是函数”。我怀疑问题在于我如何在第一个内部渲染SecondNestedComponent,并将其传递回调。代码看起来像这样:

var OutermostComponent = React.createClass({
    onUserInput: //my function,
    render: function() {
        return (
            <div>
            //other components 
                <FirstNestedComponent
                    onUserInput={this.onUserInput}
                />
            </div>
        );
    }
});

var FirstNestedComponent = React.createClass({
    render: function() {
        return (
            <div>
            //other components 
                <SecondNestedComponent
                    onUserInput={this.onUserInput}
                />
            </div>
        );
    }
});
var SecondNestedComponent = React.createClass({
    render: function() {
        var items = [];
        this.props.someprop.forEach(function(myprop) {
            items.push(<DynamicallyGeneratedListItems myprop={myprop} onUserInput={this.props.onUserInput}/>);}, this);
        return (
            <ul>
                {items}
            </ul>
        );
    }
});

How do I correctly bind callbacks to the appropriate nested components?

如何正确地将回调绑定到适当的嵌套组件?

2 个解决方案

#1


15  

You are passing this.onUserInput as a property to FirstNestedComponent. Therefore, you should access it in FirstNestedComponent as this.props.onUserInput.

您将this.onUserInput作为属性传递给FirstNestedComponent。因此,您应该在FirstNestedComponent中以this.props.onUserInput访问它。

var FirstNestedComponent = React.createClass({
    render: function() {
        return (
            <div>
                <SecondNestedComponent
                    onUserInput={this.props.onUserInput}
                />
            </div>
        );
    }
});

#2


1  

For your reference, please check the implementation I've created at jsfiddle.net/kb3gN/12007

供您参考,请查看我在jsfiddle.net/kb3gN/12007创建的实现

function ListenersService(){
    var listeners = {};
    this.addListener = function(callback){
        var id;
        if(typeof callback === 'function'){
            id = Math.random().toString(36).slice(2);
            listeners[id] = callback;
        }
        return id;
    }
    this.removeListener = function( id){
        if(listeners[id]){
            delete listeners[id];
            return true;
        }
        return false;
    }
    this.notifyListeners = function(data){
        for (var id in listeners) {
          if(listeners.hasOwnProperty(id)){
            listeners[id](data);
          }
        }
    }
}

function DataService(ListenersService){
    var Data = { value: 1 };
    var self = this;

    var listenersService = new ListenersService();
    this.addListener = listenersService.addListener;
    this.removeListener = listenersService.removeListener;
    this.getData = function(){
        return Data;
    }

    setInterval(function(){
        Data.value++;
        listenersService.notifyListeners(Data);
    }, 1000);
}
var dataSevice = new DataService(ListenersService);

var World = React.createClass({
    render: function() {
        return <strong>{this.props.data.value}</strong>;
    }
});

var Hello = React.createClass({
    getInitialState: function() {
        return {
          data: this.props.dataService.getData()
        };
    },
    componentDidMount: function() {
        this.props.dataService.addListener(this.updateHandler)
    },
    updateHandler: function(data) {
        this.setState({
          data: data
        });
    },
    render: function() {
        return (
            <div>
                Value: <World data={this.state.data} />
            </div>
        );
    }
});

React.renderComponent(<Hello dataService={dataSevice} />, document.body);

#1


15  

You are passing this.onUserInput as a property to FirstNestedComponent. Therefore, you should access it in FirstNestedComponent as this.props.onUserInput.

您将this.onUserInput作为属性传递给FirstNestedComponent。因此,您应该在FirstNestedComponent中以this.props.onUserInput访问它。

var FirstNestedComponent = React.createClass({
    render: function() {
        return (
            <div>
                <SecondNestedComponent
                    onUserInput={this.props.onUserInput}
                />
            </div>
        );
    }
});

#2


1  

For your reference, please check the implementation I've created at jsfiddle.net/kb3gN/12007

供您参考,请查看我在jsfiddle.net/kb3gN/12007创建的实现

function ListenersService(){
    var listeners = {};
    this.addListener = function(callback){
        var id;
        if(typeof callback === 'function'){
            id = Math.random().toString(36).slice(2);
            listeners[id] = callback;
        }
        return id;
    }
    this.removeListener = function( id){
        if(listeners[id]){
            delete listeners[id];
            return true;
        }
        return false;
    }
    this.notifyListeners = function(data){
        for (var id in listeners) {
          if(listeners.hasOwnProperty(id)){
            listeners[id](data);
          }
        }
    }
}

function DataService(ListenersService){
    var Data = { value: 1 };
    var self = this;

    var listenersService = new ListenersService();
    this.addListener = listenersService.addListener;
    this.removeListener = listenersService.removeListener;
    this.getData = function(){
        return Data;
    }

    setInterval(function(){
        Data.value++;
        listenersService.notifyListeners(Data);
    }, 1000);
}
var dataSevice = new DataService(ListenersService);

var World = React.createClass({
    render: function() {
        return <strong>{this.props.data.value}</strong>;
    }
});

var Hello = React.createClass({
    getInitialState: function() {
        return {
          data: this.props.dataService.getData()
        };
    },
    componentDidMount: function() {
        this.props.dataService.addListener(this.updateHandler)
    },
    updateHandler: function(data) {
        this.setState({
          data: data
        });
    },
    render: function() {
        return (
            <div>
                Value: <World data={this.state.data} />
            </div>
        );
    }
});

React.renderComponent(<Hello dataService={dataSevice} />, document.body);