相关疑难解决方法(0)

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

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

-OutermostComponent
    -FirstNestedComponent
        -SecondNestedComponent
            -DynamicallyGeneratedListItems
Run Code Online (Sandbox Code Playgroud)

单击列表项时应触发回调,即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>
        );
    }
});
Run Code Online (Sandbox Code Playgroud)

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

javascript callback reactjs react-jsx

28
推荐指数
1
解决办法
4万
查看次数

将道具传递给处理函数

我关注的是Pure React,有一个House组件需要一些构建(为简洁起见,省略了导入):

class House extends React.Component {

    state = {
        bathroom: true,
        bedroom: false,
        kitchen: true,
        livingRoom: false
    }

    flipSwitch = (action) => {
        this.setState({
            ???????????????
        });
    }

    render () {
        return (
            <>
            <RoomButton room='kitchen' handler={this.flipSwitch}/>
            <RoomButton room='bathroom' handler={this.flipSwitch}/>
            <RoomButton room='livingRoom' handler={this.flipSwitch}/>
            <RoomButton room='bedroom' handler={this.flipSwitch}/>
            </>
        );
    }
}

const RoomButton = ({room, handler}) => (
    <button onClick={handler}>
        {`Flip light in ${room}!`}
    </button>
)

ReactDOM.render (
    <House/>,
    document.getElementById('root')
)
Run Code Online (Sandbox Code Playgroud)

预期的结果:单击<room>按钮时,House组件的状态会发生变化,以反映房间内电灯开关的翻转(即,true点亮,false熄灭)。

我想知道应该 …

javascript reactjs

0
推荐指数
1
解决办法
42
查看次数

标签 统计

javascript ×2

reactjs ×2

callback ×1

react-jsx ×1