假设我想在Javascript函数内动态创建一个JSX标签树,然后将它们添加到我的React代码中。那可能吗?如果是这样,你会怎么做?
编辑:我收到<div className="msg"><p>Hello World</p></div>
作为字符串,所以我不能在没有引号的情况下返回它。另外,不使用dangerouslySetInnerHTML
。
JSX工厂
function jsxFactory() {
return '<div className="msg"><p>Hello World</p></div>'
}
反应代码
render() {
render(
{jsxFactory()}
)
}
答案 0 :(得分:1)
你可以在没有引号的情况下完成。
return <div className="msg"><p>Hello World</p></div>
答案 1 :(得分:0)
如果您明确需要在字符串中插入HTML,则需要dangerouslySetInnerHtml,大致如下:
so=> create table so81(i int);
CREATE TABLE
so=> create table so82(check (i > 2)) inherits (so81);
CREATE TABLE
so=> create table so83(check (i > 0 and i<=2)) inherits (so81);
CREATE TABLE
so=> insert into so82 select 3;
INSERT 0 1
so=> select * from only so81;
i
---
(0 rows)
so=> select * from so81;
i
---
3
(1 row)
so=> SET constraint_exclusion = on;
SET
so=> prepare so83 (int) as select 1 from so81 where i = $1;
ERROR: prepared statement "so83" already exists
so=> prepare so84 (int) as select 1 from so81 where i = $1;
PREPARE
so=> explain analyze execute so83(3);
QUERY PLAN
------------------------------------------------------------------------------------------------------------
Result (cost=0.00..42.02 rows=14 width=4) (actual time=0.037..0.039 rows=1 loops=1)
-> Append (cost=0.00..41.88 rows=14 width=0) (actual time=0.037..0.039 rows=1 loops=1)
-> Seq Scan on so81 (cost=0.00..0.00 rows=1 width=0) (actual time=0.005..0.005 rows=0 loops=1)
Filter: (i = 3)
-> Seq Scan on so82 (cost=0.00..41.88 rows=13 width=0) (actual time=0.030..0.031 rows=1 loops=1)
Filter: (i = 3)
Execution time: 0.061 ms
(7 rows)
so=> SET constraint_exclusion = off;
SET
so=> explain analyze execute so83(3);
QUERY PLAN
------------------------------------------------------------------------------------------------------------
Result (cost=0.00..84.02 rows=27 width=4) (actual time=0.030..0.033 rows=1 loops=1)
-> Append (cost=0.00..83.75 rows=27 width=0) (actual time=0.029..0.032 rows=1 loops=1)
-> Seq Scan on so81 (cost=0.00..0.00 rows=1 width=0) (actual time=0.004..0.004 rows=0 loops=1)
Filter: (i = 3)
-> Seq Scan on so82 (cost=0.00..41.88 rows=13 width=0) (actual time=0.025..0.026 rows=1 loops=1)
Filter: (i = 3)
-> Seq Scan on so83 (cost=0.00..41.88 rows=13 width=0) (actual time=0.002..0.002 rows=0 loops=1)
Filter: (i = 3)
Execution time: 0.126 ms
(9 rows)