React Native:在文本中查找子字符串,并以编程方式更改样式 [英] React Native: Find substring in text, and change style programmatically

查看:31
本文介绍了React Native:在文本中查找子字符串,并以编程方式更改样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Forgive me if I'm missing something standard here, as React isn't my default javascript dev tool. This seems like something that should fairly easily obtainable though so I figured I should ask. Is it possible, and if so how can I find a substring, and then change the style of that substring in React Native?

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 组件来以这种方式设置子字符串的样式.正确的方法是什么?

But clearly you can't dynamically add a Text component in order to style a substring this way. What is the proper method?

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

I've been looking into this more, and if I'm not mistaken... I have to make an entire array of subcomponents, keep track of the subcomponents, and then dynamically add/remove text components to this array along with the strings if I simply want to change the color of text? Someone please tell me React is not this flawed in this aspect...

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)
}

推荐答案

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

You can define an array which contains strings or objects (if you want to customize it deeper, not only it's color), and then map it into array of Text components. Here is the sample code.

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>
    );
  }
}

结果会是这样

这篇关于React Native:在文本中查找子字符串,并以编程方式更改样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆