在React.js中分离出组件

时间:2016-03-03 06:41:49

标签: reactjs

我有一个我正在使用的组件,它有一个列表,如果单击它上面的项目,将输出与该项目相关的某些数据。反应类看起来像:

SocialMenu = React.createClass({

    getInitialState: function(){
        return { focused: 0 };
    },

    clicked: function(index){

        // The click handler will update the state with
        // the index of the focused menu entry

        this.setState({focused: index});
    },

    render: function() {

        // Here we will read the items property, which was passed
        // as an attribute when the component was created

        var self = this;

        // The map method will loop over the array of menu entries,
        // and will return a new array with <li> elements.

        return (
            <div>
                <ul className="testblocks">{ this.props.items.map(function(m, index){

                    var style = '';

                    if(self.state.focused == index){
                        style = 'focused';
                    }

                    // Notice the use of the bind() method. It makes the
                    // index available to the clicked function:

                    return <li key={index} className={style} onClick={self.clicked.bind(self, index)}>{m}</li>;

                }) }

                </ul>

                <p>Selected: {this.props.items[this.state.focused]}</p> 

            </div>
        );

    }
});

编辑:

我认为组件看起来像这样:

ItemDetails = React.createClass({

    render: function() {

        return (
            <div>{this.props.item}</div>
        );
    }

});

当我将它放在SocialMenu组件中时,这可以正常工作,但是如果我想将它放在页面上的任何其他位置,则输出是未定义的。我该如何处理?

编辑:

我正在设置它,所以它进入这样的组件:

Description = React.createClass({

    getInitialState: function() {
        return { default: true };
    },

    render: function() {

        return (

            <section id="one" className="main style1">
                <div className="container">

                    <ItemDetails />

                    <span className="image fit">
                      <img src="images/pic01.jpg" alt="" />
                    </span>

                </div>
            </section>

        );

    } 

});

并且<ItemDetails />组件应显示与SocialMenu中列表中特定项目的点击相关的相关输出。如果我只是给它提供道具(<ItemDetails items={['items', 'some more'}/>),它就会打印出它所喂食的东西。

如果我将SocialMenu放在Description组件中,那么列表将显示在该部分中(我不想要)。

2 个答案:

答案 0 :(得分:1)

您可以将此代码移动到一个新组件中,该组件将当前项目作为道具。

您已经通过this.props.items[this.state.focused]获得了当前项目,因此将其作为道具传递给您的新组件

<ItemDetails item={ this.props.items[this.state.focused] } />

答案 1 :(得分:0)

Dan Abramov (Redux的创作者)非常好article 分离演示文稿和容器组件

相关问题