如何在JavaScript中插入HTML?

时间:2018-07-14 18:02:53

标签: reactjs

这是在IF中插入HTML的正确方法吗?

render() {
    return (
      <div>
            {
              if (!error) {
                <p>Sorry - there was an error</p>
              }
              else {
                <p>{this.state.data}</p>
              }
            }
     </div>
  )
}

2 个答案:

答案 0 :(得分:2)

multiple ways you can do this,都是“正确”的和/或有效的方法来完成您要尝试做的事情。这实际上取决于您的代码风格以及可读性/对您而言有意义...我将添加几种其他方式来执行此操作,以便您了解我的意思并确定最适合您的方法:)

jsx中的三元运算符

<div>
    { error ? <p>Sorry - there was an error</p> : <p>{this.state.data}</p> }
</div>

如果是逻辑&&(也称为short-circuit evaluation),则为内联

<div>
    { error && <p>Sorry - there was an error</p> }
    { !error && <p>{this.state.data}</p> }
</div>

另一种方法是在返回值之外使用if。

render() {
  const {error} = this.props
  const {data} = this.state
  if (error) {
    return <p>Sorry - there was an error</p>
  }
  return <p>{data}</p>
}

答案 1 :(得分:1)

否,在render方法中,您可以执行以下操作:

if(condition) {
return(your html)
} 
else {
return(another html)
}