search

Home  >  Q&A  >  body text

How to display React components

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粉982054449P粉982054449443 days ago587

reply all(2)I'll reply

  • P粉545910687

    P粉5459106872023-09-17 13:52:33

    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.

    reply
    0
  • P粉413704245

    P粉4137042452023-09-17 13:08:25

    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!

    reply
    0
  • Cancelreply