条件渲染和内联IF不起作用

时间:2020-10-02 12:52:08

标签: reactjs

我有两个问题:

  1. 条件渲染在统计组件上无法正常工作
  2. 第46行的
  3. 内联IF无效,因此我注释掉。我用typeof jc func检查了值,所有值都是数字

如果您发现我做错了,请告诉我。

非常感谢!

import React, {useState} from 'react'
import ReactDOM from 'react-dom'

const Feedback = (props) => (
  <button onClick={props.handleFeedback}>{props.text}</button>
)

const Statistics = (props) => {
  console.log(props);
  if (props.total.length === 0) {
    return (
      <div>empty</div>
    )
  }
  return (
    <div>
      <p>all {props.total}</p>
      <p>average {props.average}</p>
      <p>positive {props.positive}</p>
  </div>
  )
}

const App = () => {
  const [good, setGood] = useState(0)
  const [neutral, setNeutral] = useState(0)
  const [bad, setBad] = useState(0)

  const setToGood = (newValue) => () => {
    setGood(newValue)
  }

  const setToNeutral = (newValue) => () => {
    setNeutral(newValue)
  }

  const setToBad = (newValue) => () => {
    setBad(newValue)
  }

  const total = good + neutral + bad;
  const average = (good - bad) / total
  const positive =  (good / total * 100 === 0 ) ? '' : (good / total * 100)
  console.log(positive);
 

  return (
    <div>
      <h1>give feedback</h1>
      <Feedback handleFeedback={setToGood(good +1)} text="good" />
      <Feedback handleFeedback={setToNeutral(neutral +1)} text="neutral" />
      <Feedback handleFeedback={setToBad(bad +1)} text="bad" />
      <h1>statisctics</h1>
      <p>good {good}</p>
      <p>neutral {neutral}</p>
      <p>bad {bad}</p>
      <Statistics total={total} average={average} positive={positive}/>
    </div>
  )
}

ReactDOM.render(
  <App />, 
  document.getElementById('root')
)

1 个答案:

答案 0 :(得分:0)

IF内不要使用props.total.length,因为总数是number类型而不是字符串。

相关问题