useMemo设置组件样式

我有一个称为样式的函数,该函数在其中检查参数值以返回Card组件的颜色,一个朋友告诉我尝试使用useMemo仅在参数更改时运行该函数,但是我可以没有找到一种方法来理解这个问题。我如何通过不需要运行该功能的条件?

function styling(votes) {
  let styling = '#696969'

  if (votes > 0) {
    styling = '#008000'
  } else if (votes < 0) {
    styling = '#B22222'
  }

  return styling
}


function App() {

  const [content,setContent] = useState(images)

  const upVote = (param) => {
    setContent(() => {
      for(let i = 0; i < content.length; i++) {
        if (content[i].id === param){
          content[i].votes = content[i].votes+1
        } 
      }
      return [...content]
    })
  }

  const downVote = (param) => {
    setContent(() => {
      for(let i = 0; i < content.length; i++) {
        if (content[i].id === param){
          content[i].votes = content[i].votes-1
        } 
      }
      return [...content]
    })
  }



  return (
    <div classname="App">
      <div classname="grid">
        {content.map((picture,index) => {
          return <Card key={index} picture={picture} upVote={upVote} downVote={downVote} style={styling(picture.votes)}/>
          })
        }
      </div>
    </div>
  )
}

export default App
chlinboy 回答:useMemo设置组件样式

您传递了可以更新数组中函数结果的属性,例如useMemo(() => { ... },[propOne,propTwo]),就像许多其他钩子一样。

在您的情况下,您会通过votes

,

style道具需要一个对象。 要使其正常工作,您必须进行更改:

<Card
  key={index}
  picture={picture}
  upVote={upVote}
  downVote={downVote}
  style={{
    color: styling(picture.votes)
  }}
/>

或者从函数中返回对象,然后直接使用,就可以使用了。

,
 //in parent component of App:
 return <Card key={index} picture={picture} upVote={upVote} downVote={downVote} votes={picture.votes}/>

// in your child functional component votes is a prop passed in dynamically,let's memoize it to `styleBaseOnVote` to stop unnecessary re-renders.
   function ChildComponent(picture: <yourPictureObjInterface>,upVote: function,downVote:function,votes: Number): ReactElement {
    const styleBaseOnVote = useMemo(() => {
    let styling = '#696969'

  if (votes > 0) {
    styling = '#008000'
  } else if (votes < 0) {
    styling = '#B22222'
  }

  return styling
    },[votes])

   return <div style={{color: styleBaseOnVote}}
}

本文链接:https://www.f2er.com/3166593.html

大家都在问