How to display React components
P粉982054449
P粉982054449 2023-09-16 22:40:46
0
2
518

Can the following content be displayed like this: jsx?

//编写一个返回`jsx`的js函数
function child(label, value){
  return (
    <h3>
     {label}: {value}
    </h3>
  )
}

export default function Parent(){
  const [state, setState] = useState({label:"", value:""})
  const {label, value} = state;
  
  return (
    // 然后调用函数显示`jsx`
    <>{test(label, value)}</>
  )
}

Or is it better to write React functional components:

function Child({state}){
  return (
    <h3>
     {state.label}: {state.value}
    </h3>
  )
}

export default function Parent(){
  const [state, setState] = useState({label:"", value:""})
  
  return (
    <Child state={state} />
  )
}
P粉982054449
P粉982054449

reply all(2)
P粉545910687

The second method looks simpler and readable. Remember, the more readable you make the code, the larger the project becomes, the easier it is to manage. Furthermore, this approach is the most common practice for building React components.

P粉413704245

Best practice is to render it as a React component.

The reason is that while just using functions is still feasible for very simple components, you may want to change it in the future and add more "React-like" functionality like hooks. At that point, it can go wrong, and React usually won't tell you that's what's causing your application to go wrong. If this happens, it can be a headache to find the error, especially if the function is in another file.

An example of how it can go wrong when using error bounds can be found in this article.

According to this Stack Overflow answer, the function call approach may be faster in terms of performance, but in my opinion not using the function at all is the safer option in this case.

So if you think you are careful enough, no one will stop you. But make sure not to get yourself into trouble. good luck!

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!