【问题标题】:react native make part of TextInput to be bold or italics at run time反应原生使 TextInput 的一部分在运行时变为粗体或斜体
【发布时间】:2018-07-22 21:47:40
【问题描述】:

我有一个简单的 TextInput 应用程序,如下所示:

export default class App extends Component<Props> {
  constructor(props) {
    super(props);
    this.state = { textValue: '' };
    this.handleTextInputChange = this.handleTextInputChange.bind(this);
  }

  handleTextInputChange(input) {
    this.setState({textValue: input})
  }

  render() {
    return (
      <KeyboardAvoidingView
         behavior="padding"
         style={{flex:1}}
         enabled>
        <TextInput
          style={styles.textInputStyle}
          multiline={true}
          onChangeText={this.handleTextInputChange}
          value={this.state.textValue}
        />
      </KeyboardAvoidingView>
    );
  }
}

我想做的是,当我在 TextInput 中写 ##hello 时,TextInput 屏幕中即时呈现的是 hello 粗体,就像在 Dropbox Paper 中进行 Markdown 编辑一样。同样,当我写_hello_ 时,我在屏幕上看到的内容是hello 斜体。

Screen

我可以这样做吗? (让TextInput的一部分有不同的风格)

到目前为止,TextInput 似乎只能采用一种样式?

如果我们不能有不同样式的 TextInput,有什么办法可以替代(某种 TextInput)的粗体、斜体、更大、更小...

【问题讨论】:

    标签: react-native mobile


    【解决方案1】:

    我很确定您可以像这样在 TextInput 中嵌套 Text:

    <TextInput>
        <Text style={{fontWeight:'bold'}}>I'm bold</Text>
    </TextInput>
    

    只需解析文本并根据需要附加不同样式的文本。

    【讨论】:

    • 也许这曾经可以工作,但它在 React Native 0.61 中不起作用
    • 它确实有效。但要注意 onChangeText 会给你原始文本(没有粗体、斜体、..)
    【解决方案2】:

    您可以使用this lib react-native-easy-markdown 来呈现markdown 文本并像这样隐藏文本输入并呈现markdown 组件。 :

    import React, { Component } from 'react';
    import { StyleSheet, View, TextInput, TouchableOpacity } from 'react-native';
    import Markdown from 'react-native-easy-markdown';
    
    export default class App extends Component {
      state = { text: 'type here ...' };
      onClick = e => {
        this.textInput.focus();
      };
      render() {
        return (
          <View style={styles.container}>
            <TextInput
              ref={ref => (this.textInput = ref)}
              style={{ position: 'absolute', left: -1000, top: -1000 }}
              onChangeText={text => this.setState({ text })}
            />
            <TouchableOpacity onPress={this.onClick}>
              <Markdown>{this.state.text}</Markdown>
            </TouchableOpacity>
          </View>
        );
      }
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
      },
    });
    

    这里是代码演示:

    【讨论】:

    • 非常感谢!
    • 您将失去光标,您将无法正确编辑文本(剪切、复制、粗体等)供参考。
    猜你喜欢
    • 1970-01-01
    • 2012-01-21
    • 2023-03-20
    • 1970-01-01
    • 2016-07-28
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    相关资源
    最近更新 更多