有条件地展示道具

时间:2018-11-28 11:03:43

标签: reactjs

当前,我将所有任务都列在一个组件中。我想制作多个列表,只显示task.owner === listOwner(从父组件向下传递)的任务。我应该在地图功能之外执行此操作吗?我是个新手,所以请让我知道我是否可以更好地或在一个更好的地方问这个问题:)

  render() {
    const { tasks } = this.props.task;
    const { listOwner }  = this.props;
    return(
      <Container style={{marginBottom: 50}}>
        <div>List owner: {listOwner}</div>
        <ListGroup>
          <TransitionGroup className="task-list">
            {tasks.map(({ _id, name, tokenValue, owner }) => (
                <CSSTransition key={_id} timeout={500} classNames="fade">
                  <ListGroupItem>
                    <Button
                      className="remove-btn"
                      color="danger"
                      size="sm"
                      onClick={this.onDeleteClick.bind(this, _id)}
                    >
                      &times;
                    </Button>
                    <div className="inline"><div className="field-label">Task:</div> {name}</div>
                    <div className="inline"><div className="field-label">Value (BRPT):</div> {tokenValue}</div>
                    <div className="inline"><div className="field-label">Owner:</div> {owner}</div>

                    <div className="float-right inline"><MemberDropdown taskId={_id} /></div>
                  </ListGroupItem>
                </CSSTransition>
            ))}
          </TransitionGroup>
        </ListGroup>
      </Container>
    )
  }

1 个答案:

答案 0 :(得分:1)

有两种方法可以做到:

1。)filter() maprender之前的项目。

2。)在render中有一个条件语句。

这取决于您拥有的应用程序结构,很难从您发布的内容中分辨出来。

如果您在父组件中拥有所有数据,则可以进行过滤,例如

const completedTasks = tasks.filter(t => t.completed)
const remainingTasks = tasks.filter(t => !t.completed)

然后将这些数组传递给您的组件,例如:

<TaskList items={completedTasks} />
<TaskList items={remainingTasks />

这里是一个示例:

import React from "react";
import ReactDOM from "react-dom";

const tasks = [
  { title: "walk the dog", completed: false },
  { title: "get some milk", completed: true }
];

const TaskItem = ({ item }) => {
  return <li>{item.title}</li>;
};

const TaskList = ({ tasks }) => {
  return (
    <ul>
      {tasks.map(t => (
        <TaskItem item={t} />
      ))}
    </ul>
  );
};

function App() {
  const completedTasks = tasks.filter(t => t.completed);
  const remainingTasks = tasks.filter(t => !t.completed);

  return (
    <div className="App">
      Completed
      <TaskList tasks={completedTasks} />
      Remaining
      <TaskList tasks={remainingTasks} />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

CodeSandbox链接here