【问题标题】:TextInput onChange event receives text object not stringTextInput onChange 事件接收文本对象而不是字符串
【发布时间】:2016-03-29 21:31:54
【问题描述】:

我正在尝试从 ListView 组件中的 TextInput onChange 事件更新 redux 状态。就我而言,我正在显示比率列表。我想将编辑后的比率解析为其两个值。但是,传递给setItem 方法的text 值不是我预期的字符串,但它似乎是一个Text 或TextInput 对象。

editItem 是一个 redux 操作,它对 redux 状态执行编辑。

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

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

【问题讨论】:

    标签: javascript react-native redux


    【解决方案1】:

    TextInput 文档看来,您需要使用 onChangeText 事件。

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

    【讨论】:

    • 你可以使用任何一个。 onChangeText 导致同样的问题
    • 其实这是一个很好的线索!使用 onChangeText 会生成一个包含 text 属性的对象,该属性带有已更改的文本字符串,只需极少的更改即可将其取出。谢谢!如果您想编辑它以添加该详细信息,我会接受您的回答...
    猜你喜欢
    • 2020-01-14
    • 2013-03-23
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 2011-08-06
    • 2014-02-08
    相关资源
    最近更新 更多