我在显示/隐藏某些元素时遇到了麻烦。基本上,我有一个li的动态列表,并且在li内,我有一个标签,当您单击li时,我想隐藏标签并显示输入。通常,使用jQuery就像
$('#element').hide() $('#element2').show()
我不太了解如何使用当前的布局实现这一目标

class EntriesTable extends React.Component {
    constructor(props) {
        super(props);

        console.log(this.props.plannerId);
        this.state = {
            tasks: [],
            plannerId: this.props.plannerId,
        };

        var state = this.state;
    }

    componentDidMount() {
        this.getTasks(this.state.plannerId);
    }

    EditTask(id) {
        console.log(id);
        var spanEl = id + 'taskSpan';
        var inputEl = id + 'taskInput';
        //hide this span
        //show input
        $(spanEl).hide();
        $(inputEl).show();

        //when save

        //hide input
        //update task
        //show span
    }

    updateTask(id, name) {
        $.ajax({
            type: "GET",
            url: "/Task/Update",
            data: { id: id, name: name },
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                console.log(data);
                //this.setState({ tasks: data.ReturnObject, loading: false });
            }.bind(this),
            error: function (xhr, status, err) {
                console.log(err);
            }
        });
    }

    createTask(name) {
        //make api call to create planner here.

        var data = {
            Name: name,
            PlannerId: model.plannerId,
            Status: "Not Complete",
            Description: "",
            Affiliation: "",
            Footprint: "",
            Created: new Date(),
            Modified: null,
        };

        $.ajax({
            type: "POST",
            url: "/Task/Add",
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                console.log(data);
                this.getTasks(model.plannerId);
            }.bind(this),
            error: function (xhr, status, err) {
                console.log(err);
            }
        });
    }

    getTasks(id) {
        this.setState({ tasks: [], loading: true });
        $.ajax({
            type: "GET",
            url: "/Task/GetAll",
            data: { id: id },
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                console.log(data);
                this.setState({ tasks: data.ReturnObject, loading: false });
            }.bind(this),
            error: function (xhr, status, err) {
                console.log(err);
            }
        });
    }

    render() {
        const tasks = this.state.tasks.map((task) => {
            var spanId = task.Id + "taskSpan";
            var inputId = task.Id + "taskInput";
            return (
               <li key={task.Id} className="list-group-item" style={{minHeight: '50px'}}>
                   <div className="pull-left" style={{width: '50%'}}>
                       <span id={spanId} onClick={this.EditTask.bind(this, task.Id) }>{task.Name}</span>
                       <input id={inputId} type="text" style={{ display: 'none' } } />
                   </div>
                   <div className="pull-right" style={{marginTop: '-5px', width: '50%'}}>
                       <div className="pull-right">
                            <button className="btn btn-default">Add</button>
                            <button className="btn btn-default">Edit</button>
                        </div>
                   </div>
               </li>
            );
        });
        return (
          <div className="table-wrapper">
            <div className="task-container">
                <h3>{this.props.rowName}</h3>
            </div>
            <ul id="tasksContainer">
                {tasks}
                <li className="list-group-item list-group-item-last"><input type="button" value="Add Task" onClick={this.addTask.bind(this)} className="btn btn-success btn-override" /></li>
            </ul>
          </div>

      );
    }
};


我确实看到了其他的SO,它们告诉您使用变量,然后通过更改变量来显示/隐藏,但是我不确定这是否满足我的需要,因为我有一个动态列表,它不仅是单个元素,试图显示或隐藏。

最佳答案

class EntriesTable extends React.Component {
    constructor(props) {
        super(props);

        console.log(this.props.plannerId);
        this.state = {
            editableTasks: [],
            tasks: [],
            plannerId: this.props.plannerId,
        };

        var state = this.state;
        /* This isn't completely necessary but usually it is recommended you
         * bind the class method in the constructor so it isn't bound on each
         * render
         */
        this.EditTask = this.EditTask.bind(this);
    }

    componentDidMount() {
        this.getTasks(this.state.plannerId);
    }

    EditTask(id) {
        /* So jQuery and react are kind of at odds with each other on fundamentals
         * React is supposed to be declarative whereas jQuery is imperative. Using
         * jQuery and React together is typically discouraged unless there is a real
         * need for it. In React you are supposed to define how you want the UI to render
         * based on some variables. You have two options available to you props and state.
         * props are passed from the parent and are immutable. state is managed within that
         * component and is mutable. So we have added a variable called editableTasks to your
         * state that will contain an array of all editable tasks. Instead of trying to hide
         * or show items here, we are simply going to add the id of now editable task to that
         * array
         *
         */
        var nextState = this.state;
        nextState.editableTasks.push(id);
        this.setState(nextState);
    }

    updateTask(id, name) {
        $.ajax({
            type: "GET",
            url: "/Task/Update",
            data: { id: id, name: name },
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                console.log(data);
                //this.setState({ tasks: data.ReturnObject, loading: false });
            }.bind(this),
            error: function (xhr, status, err) {
                console.log(err);
            }
        });
    }

    createTask(name) {
        //make api call to create planner here.

        var data = {
            Name: name,
            PlannerId: model.plannerId,
            Status: "Not Complete",
            Description: "",
            Affiliation: "",
            Footprint: "",
            Created: new Date(),
            Modified: null,
        };

        $.ajax({
            type: "POST",
            url: "/Task/Add",
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                console.log(data);
                this.getTasks(model.plannerId);
            }.bind(this),
            error: function (xhr, status, err) {
                console.log(err);
            }
        });
    }

    getTasks(id) {
        this.setState({ tasks: [], loading: true });
        $.ajax({
            type: "GET",
            url: "/Task/GetAll",
            data: { id: id },
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                console.log(data);
                this.setState({ tasks: data.ReturnObject, loading: false });
            }.bind(this),
            error: function (xhr, status, err) {
                console.log(err);
            }
        });
    }

    render() {
        const tasks = this.state.tasks.map((task) => {
            var editable = this.state.editableTasks.filter(id => id === task.Id).length > 0;
            /* Now here we are going to check whether this item is editable
             * based on id. So we assign a variable that will eval to a bool
             * based on whether when you filter editableTasks to see if it contains
             * the current items id the length is greater than 0.
             *
             * Now below instead of applying some id attribute we are going to return either
             * the input or the span based on whether it is editable using a ternary operation
             *
             */
            return (
               <li key={task.Id} className="list-group-item" style={{minHeight: '50px'}}>
                   <div className="pull-left" style={{width: '50%'}}>
                       {editable ? <input type="text" /> : <span onClick={this.EditTask( task.Id)}>{task.Name}</span>}

                   </div>
                   <div className="pull-right" style={{marginTop: '-5px', width: '50%'}}>
                       <div className="pull-right">
                            <button className="btn btn-default">Add</button>
                            <button className="btn btn-default">Edit</button>
                        </div>
                   </div>
               </li>
            );
        });
        return (
          <div className="table-wrapper">
            <div className="task-container">
                <h3>{this.props.rowName}</h3>
            </div>
            <ul id="tasksContainer">
                {tasks}
                <li className="list-group-item list-group-item-last"><input type="button" value="Add Task" onClick={this.addTask.bind(this)} className="btn btn-success btn-override" /></li>
            </ul>
          </div>

      );
    }
};


因此,上述内容应可用于使项目可编辑。现在,它不处理实际编辑它们或将它们返回到不可编辑状态。但这应说明您应如何以“ react 方式”完成此任务。

我鼓励您放弃jQuery。 jQuery将使您的React代码更难管理,也难以接受React方式。如果您需要一些用于ajax请求的内容,则有很多同样适合的小型库(强烈建议您使用superagent,但快速的Google可以将您带到其他许多库)

如果您还有其他问题,请告诉我。

关于reactjs - 如何动态显示/隐藏react中的项目列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39737337/

10-10 11:09
查看更多