Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

javascript - React.js how to pass callbacks to child components?

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:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...