如何在ReactJS中基于点击索引切换组件

时间:2016-08-05 18:59:18

标签: reactjs

var Comp = React.createClass({
    getInitialState: function(){
        return {hide: false};
    },
    toggle: function(){
        this.setState({hide: !this.state.hide});
    },
    render: function() {
        return <div>
            <button onClick={this.toggle}>toggle</button>    
            <div className={'hide-' + this.state.hide}>Hi there</div>

      <button onClick={this.toggle}>toggle</button>    
            <div className={'hide-' + this.state.hide}>Hi there</div>

      <button onClick={this.toggle}>toggle</button>    
            <div className={'hide-' + this.state.hide}>Hi there</div>

      <button onClick={this.toggle}>toggle</button>    
            <div className={'hide-' + this.state.hide}>Hi there</div>
        </div>;
    }
});

ReactDOM.render(
    <Comp />,
    document.getElementById('container')
);

https://jsfiddle.net/9lessons/aLd1w6qs/3/

2 个答案:

答案 0 :(得分:3)

您正在使用公共状态变量来切换div。由于它在所有div之间共享,因此可变的可见性会同时改变所有这些。

您可以为每个div创建一个separete状态变量,例如hide1,hide2 ..... hideN。

或者

尝试另一种方法 - 创建单独的组件本身。

var ToggleableComp = React.createClass({
    getInitialState:function() {
        return {hide: false};
    },
    toggle: function(){
        this.setState({hide: !this.state.hide});
    },
    render: function() {
      return (
        <div>
        <button onClick={this.toggle}>toggle</button>    
            <div className={'hide-' + this.state.hide}>{this.props.children}</div>
        </div>
      );
    }
});

var Comp = React.createClass({
    render: function() {
        return (
           <div>
             <ToggleableComp>Json Data 1</ToggleableComp>
             <ToggleableComp>Json Data 2</ToggleableComp>
             <ToggleableComp>Json Data 3</ToggleableComp>
             <ToggleableComp>Json Data 5</ToggleableComp>
        </div>
      );
    }
});

ReactDOM.render(
    <Comp />,
    document.getElementById('container')
);

选中此fiddle

答案 1 :(得分:0)

此问题的解决方案,请尝试点击评论按钮。

var EachCom = React.createClass({
    getInitialState: function(){
    return { showComment: false };
    },
    commentLink: function()
    {
    this.setState({ showComment: !this.state.showComment });
    this.renderCommentForm;
    },
    renderCommentForm: function()
    {

if(this.state.showComment)
{
return (<CommentForm />)
}

},
render: function(){
return <div><br/>
<button onClick={this.commentLink}> comment </button>
{this.renderCommentForm()}
 </div>
}
});

var TaskList = React.createClass({


    render: function(){
        return <div>
            {this.props.items.map((task, taskIndex) => 
                <div key={taskIndex}>
                    {task}
                    <EachCom />

                </div>
            )}
        </div>;
    }
 });

http://jsfiddle.net/9lessons/t37Lk6p4/171/