简体   繁体   English

在 React 中创建 JSX 后如何为其添加样式?

[英]How to add styling to a JSX after its creation in React?

Suppose I have a JSX element which is returned from some hidden source, lets assume for instance that the hidden source returns JSX like this:假设我有一个从某个隐藏源返回的 JSX 元素,假设隐藏源返回 JSX,如下所示:

getElement = () => {
  return (<h1>Some Test </h1>)
}

and I store that JSX in some variable, eg我将该 JSX 存储在某个变量中,例如

this.h = this.getElement()

How can I change the style of h before finally rendering it to the DOM without adding external CSS?在不添加外部 CSS 的情况下,如何在最终将其渲染到 DOM 之前更改h的样式?

Since you write from a hidden source I assume you can not change the element (black box)由于您from a hidden source因此我假设您无法更改元素(黑框)

What you can do is change the style props of h :您可以做的是更改h的样式道具:

this.h = this.getElement()
this.h.props.style = { ...this.h.props.style, { backgroundColor: "#00ff00" } }

Here's an example, just using React Native, but same principle这是一个例子,只是使用 React Native,但原理相同


How to figure it out:如何弄清楚:

Inspecting the output of getElement with console.log(getElement) would show you that <h1> is transpiled into React.createElement(...) and console.log(getElement()) would show you the returned object, where you can inspect props.style使用console.log(getElement)检查getElement的 output 会显示<h1>已转换为React.createElement(...)console.log(getElement())会显示返回的 object,您可以在其中检查props.style

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

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