如何从道具设置条件?

时间:2018-03-27 14:16:14

标签: javascript reactjs if-statement ecmascript-6 conditional

在我的反应组件中

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

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

完美无缺,除非道具没有任务。什么是反应中处理这个的最好方法。

问题:页面无法渲染,因为无法设置hasTask,因为没有名为task的道具。

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

2 个答案:

答案 0 :(得分:2)

  

页面无法渲染,因为无法设置hasTask,因为没有名为task的道具。

我认为您要问的问题是:如果没有this.props.task,我该如何渲染 else ?因为当你没有this.props.task时,你的工作就好了。

&#13;
&#13;
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")
);
&#13;
<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>
&#13;
&#13;
&#13;

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

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

示例:

&#13;
&#13;
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")
);
&#13;
<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>
&#13;
&#13;
&#13;

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

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

示例:

&#13;
&#13;
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")
);
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

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