简体   繁体   English

在 React Native 中附加 JSX

[英]Appending JSX in React Native

I'm searching for a way to add a JSX element programmatically in React Native.我正在寻找一种在 React Native 中以编程方式添加 JSX 元素的方法。 Not conditionally.不是有条件的。

It needs to be independent function, so far I couldn't find anything about this.它需要是独立的function,到目前为止我找不到任何关于这个的信息。 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.假设我用 useEffect 调用这个 function,它应该添加我在 function 中的任何 jsx。直到此时,我总是看到像推入数组或类似的东西。

UPDATE更新

Equivalent behaviour that works on web;适用于 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.如您所见,我们不必在应用程序中接触任何 JSX。 Reaching document.body and appending whatever we want is possible in React Web. But how can we achieve this in React Native?在 React Web 中可以到达 document.body 并附加我们想要的任何内容。但是我们如何在 React Native 中实现这一点?

Not quite sure what you want to do, but as for to add a JSX manually.不太确定你想做什么,但关于手动添加JSX Here's the answer.这就是答案。

JSX is already part of the language in most of the cases.在大多数情况下, JSX已经是语言的一部分。

  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.因此,在大多数常见情况下,如果你在其他地方继续使用React ,那么变量a会保存一个React元素,而不会出现任何编译错误。

You might wonder what a actually really holds, it's an object:你可能想知道a到底是什么,它是 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.所以你可以看到上面的唯一依赖项是TextReactElement Symbol。 As long as you can resolve them, you are good to export this to anywhere.只要你能解决它们,你就可以把它导出到任何地方。 The latter is normally taken care by Babel.后者通常由 Babel 负责。

NOTE:笔记:

There's a difference between Text and <Text /> . Text<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.如果你只是想导出一个Text ,它是一个 function 组件,那里有在线教程,你也可以深入任何第三方库,因为基本上这就是他们所做的,导出Text以便其他人可以使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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