如何从 props 设置条件?

How do I set a condition from props?

在我的 React 组件中

render() {
let hasTask = this.props.task

return <div>
 {hasTask && <div> I have a task </div>}
</div>
 }

工作得很好,除非道具没有任务。在反应中处理这个问题的最佳方法是什么。

问题:页面不渲染是因为没有task的props无法设置hasTask。

对于这个简单的问题,我真的很抱歉。我必须从某个地方开始。

render(
 let hasTask = this.props.task
 return (<div>{hasTask? <div>I have a task</div>:<div/>}</div>)
)

The page does not render because hasTask can't be set because there is no props called task.

我想你想问的是:如果没有 this.props.task,我如何渲染 else?因为当没有 this.props.task:

时,你所拥有的就可以正常工作

class Example extends React.Component {
  render() {
    let hasTask = this.props.task

    return <div>
      {hasTask && <div> I have a task </div>}
      </div>;
  }
}

ReactDOM.render(
    <div>
    Example without task:
    <Example />
    Example with task:
    <Example task="foo" />
    </div>,
    document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

如果是这样,答案是人们通常使用条件运算符:

return <div>
  {hasTask ? <div> I have a task </div> : <div> I don't have a task </div> }
  </div>;

示例:

class Example extends React.Component {
  render() {
    let hasTask = this.props.task

    return <div>
      {hasTask ? <div> I have a task </div> : <div> I don't have a task </div> }
      </div>;
  }
}

ReactDOM.render(
    <div>
    Example without task:
    <Example />
    Example with task:
    <Example task="foo" />
    </div>,
    document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

如果你两次都想要 div,你可以稍微简化一下:

return <div>{hasTask ? "I have a task" : "I don't have a task"}</div>;

示例:

class Example extends React.Component {
  render() {
    let hasTask = this.props.task

    return <div>{hasTask ? "I have a task" : "I don't have a task"}</div>;
  }
}

ReactDOM.render(
    <div>
    Example without task:
    <Example />
    Example with task:
    <Example task="foo" />
    </div>,
    document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>