TextInput onChange事件接收的是文本对象而不是字符串

TextInput onChange event receives text object not string

本文关键字:文本 对象 字符串 onChange 事件 TextInput      更新时间:2023-09-26

我正在尝试从ListView组件中的TextInput onChange事件更新redux状态。在我的例子中,我显示了一个比率列表。我想将编辑后的比率解析为两个值。然而,传递到setItem方法中的text值并不是我所期望的字符串,而是一个Text或TextInput对象。

editItem是对冗余状态进行编辑的冗余动作。

如何获取输入字符串值,以便将其传递给操作?

class DataList extends Component {
  constructor(props) {
    super(props);
    // Bind the function so we can use it on onPress event
    this.renderRow = this.renderRow.bind(this);
    const { data } = this.props.currentData;
    this.dataSource = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2
    })
  }
  render() {
    // Keep dataSource up to date with redux state
    const { data } = this.props.currentData;
    const dataSource = this.dataSource.cloneWithRows(data.list);
    return (
      <View>
        <ListView
          dataSource={dataSource}
          renderRow={this.renderRow}
          renderSeparator={(sectionID, rowID) => <View key={`${sectionID}-${rowID}`} style={styles.separator} />}
          style={[styles.list, {height: windowDims.height}]}
          initialListSize={1}
        />
      </View>
    )
  }
  setItem(index, text) {
    console.log (index + "; [" + text + "]")
    console.log (text) // Prints out what looks like a Text or TextInput object
    var { data } = this.props.currentData;
    var numerator = parseInt (text.substring (0, text.indexOf('/'))) // Fails as it does not find a string
    var denominator = parseInt (text.substring (text.indexOf('/')+1))
    this.props.dispatch(editItem(index, { numerator: numerator, denominator: denominator }));
  }
  renderRow(rowData, sectionID, rowID) {
    return (
        <View style={styles.rowContainer}>
          <TextInput
            style={styles.textInput}
            keyboardType={'numeric'}
            onChange={(text) => this.setItem(rowID, text)}
            value={rowData.numerator + "/" + rowData.denominator}
          />
        </View>
    );
  }
}

在TextInput文档中,我认为您需要使用onChangeText事件。

更新:使用onChangeText将为您提供一个对象,该对象包含一个具有更改后的文本字符串的文本属性。