渲染包含样式代码的字符串

时间:2018-12-12 15:50:03

标签: javascript react-native

我有一个包含问题和答案的数组。我有一个将导入数组然后输出内容的组件。

但是,我现在需要添加特定的样式。在我看来,应该可以将内联样式添加为字符串文字,但这是行不通的:

questionList.js

import React from "react";
import { Text } from "react-native";

export const questions = [
  {
    question: `This is regular text: ${(
      <Text style={{ fontWeight: "bold" }}>
        But this should be bold!
      </Text>
    )This is also regular text`,
    choices: [
      "Answer 1",
      "Answer 2",
      "Answer 3",
      "Answer 4",
    ]
  }
]

RenderQuestion.js

import React from "react";
import { Text, View } from "react-native";
import { questions } from "../Data/questionList";

export const Question = () => (
  <View>
    <Text>{questions[0].question}</Text>
  </View>
);

我得到的输出看起来像: This is regular text: [object Object] This is also regular text

有没有办法做到这一点? 应该我是这样吗?

1 个答案:

答案 0 :(得分:1)

您需要修正问题数据,使其具有组成部分而不是字符串作为问题。

类似的事情应该起作用:

export const questions = [
  {
    question: <Text>This is regular text: 
      <Text style={{ fontWeight: "bold" }}>
        But this should be bold!
      </Text>
      This is also regular text</Text>,
    choices: [
      "Answer 1",
      "Answer 2",
      "Answer 3",
      "Answer 4",
    ]
  }
];

另一种选择是,如果您希望数据更具可读性并且更容易应用简单样式,则可以使用某些markdown模块。

例如react-native-simple-markdown