【问题标题】:React Native: Find substring in text, and change style programmaticallyReact Native:在文本中查找子字符串,并以编程方式更改样式
【发布时间】:2019-09-05 14:58:36
【问题描述】:

如果我在这里遗漏了一些标准,请原谅我,因为 React 不是我默认的 javascript 开发工具。这似乎应该很容易获得,所以我想我应该问。有没有可能,如果可以,我怎样才能找到一个 substring,然后在 React Native 中更改该 substring 的样式?

示例:

render() {
    return (
        <View>
            <Text>
                {this.state.myText}
            </Text>
        </View>
    );
}

componentDidMount() {
    setTimeout(() => {
        let newStr = this.state.myText.replace('green',  '<Text style={{ color: "green" }}>green</Text>');
        this.setState({ myText: newStr });
    },
    3000)
}

但很明显,您不能动态添加 Text 组件来以这种方式设置子字符串的样式。正确的方法是什么?

编辑:

我一直在研究这个问题,如果我没记错的话……我必须创建一个完整的子组件数组,跟踪子组件,然后动态地将文本组件添加/删除到这个数组中如果我只是想改变文本的颜色,用字符串?有人请告诉我 React 在这方面没有这个缺陷......

使用的最终代码:

render() {
    return (
        <View style={styles.container}>
          <Text>
            {this.state.textItems.map(item => (
              <Text style={{ color: item === 'green' ? 'green' : 'black' }}>{item}</Text>
            ))}
          </Text>
        </View>
    );
}

componentDidMount() {
    setTimeout(() => {
        this.setState({ textItems: this.state.textItems[0].split((/(green)/)) });
    },
    3000)
}

【问题讨论】:

  • 文本模块不能是父模块。无法将文本插入文本模块。

标签: reactjs react-native


【解决方案1】:

您可以定义一个包含字符串或对象的数组(如果您想更深入地自定义它,而不仅仅是颜色),然后将其映射到Text 组件的数组中。这是示例代码。

class Sample extends Component {
  // You can manipulate this items array, using setState
  state = {
    items: ['black', 'green', 'red']
  }

  render() {
    return (
      <Text>
        {textItems.map(item => (
          <Text style={{ color: item }}>{item}</Text>
        ))}
      </Text>
    );
  }
}

结果会是这样的

【讨论】:

  • 我真的不想相信这是必须做的事情,但我读过的所有内容都说是,这是唯一更改子字符串的方法风格。谢谢。
  • 一开始看起来很别扭,但你会适应反应。别客气! @Z.Bagley
【解决方案2】:

您应该通过使用样式来做到这一点。有很多方法,但这是一种:

constructor(){
  this.state = {color: "black", myText: "hello"};
}
render() {
    return (
        <View>
            <Text style={{color: this.state.color}}>
                {this.state.myText}
            </Text>
        </View>
    );
}

componentDidMount() {
    setTimeout(() => {
        this.setState({ color: "green" });
    },
    3000)
}

【讨论】:

  • 希望在搜索时更改部分主字符串的颜色(子字符串),而不是整个字符串。
  • @Z.Bagley 所以你有一个搜索框并且想要更改与搜索框文本完全匹配的文本颜色?
  • 我有从不同位置动态提取的文本(想象一本书或网页中的一段),并且想要识别特定单词的所有出现(也以编程方式动态找到)。我接受的答案符合我的要求,但我总是愿意接受其他建议。
  • @Z.Bagley 原谅我,但我不明白该答案如何支持根据其他文本进行动态颜色更改。我没有给你的答案,但我很想看看你的成果
  • 请随时查看我对我使用的最终代码的更新答案。这会根据文本拆分“绿色”并设置样式。在我的实际用例中,我将根据更复杂的逻辑对其进行样式设置,但总体思路仍然存在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-19
  • 2017-12-14
  • 2017-11-23
相关资源
最近更新 更多