简体   繁体   中英

Appending JSX in React Native

I'm searching for a way to add a JSX element programmatically in React Native. Not conditionally.

It needs to be independent function, so far I couldn't find anything about this. Let me give you code example;

const appendJSX = () => { 
  
 const jsx = <Text> Hello! </Text>

  append(jsx) // <---- can we do something like this?
 } 

let's say I call this function with useEffect and it should add whatever jsx I have inside the function. Up until this point I always see things like pushing inside of an array or something like that.

UPDATE

Equivalent behaviour that works on web;

 useEffect(() => {
 const div = document.createElement("div");
 div.innerText = "appended div"
 document.body.append(div)
 }, [])

As you can see we don't have to touch any JSX in application. Reaching document.body and appending whatever we want is possible in React Web. But how can we achieve this in React Native?

Not quite sure what you want to do, but as for to add a JSX manually. Here's the answer.

JSX is already part of the language in most of the cases.

  const a = <Text />
  export default a

Will translates into:

  const a = createElement(Text, null, null)
  export default a

Therefore in most of common cases, if you continue using React somewhere else, then the variable a holds a React element without any compilation error.

You might wonder what a actually really holds, it's an object:

  const a = { 
    $$typeof: Symbol(ReactElement), 
    props: null, 
    type: Text 
  }

So you can see the only dependencies in above piece is Text and the ReactElement Symbol. As long as you can resolve them, you are good to export this to anywhere. The latter is normally taken care by Babel.

NOTE:

There's a difference between Text and <Text /> . If you just want to export a Text which is a function component, there'll tutorial online, also you can dig into any third party library, because essentially that's what they do, export Text so other people can use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM