setState()将一个Proxy对象添加到property而不是react native中的字符串值

时间:2017-08-21 18:30:18

标签: react-native setstate

这是一个非常奇怪的问题,我确信我忽略了一些非常简单的事情。

当我加载新组件AddNewCategory时,我最初将一个空字符串设置为text上的this.state属性。登录控制台也会将text值显示为空。

我使用onChange组件的Button更新此值。我知道text属性到目前为止已按预期更新,因为输入字段的值会相应更改。

<Button onChange={text=>this.setState({})}>

但是当我尝试检索text属性的值时,我发现text不是字符串而是分配了Proxy对象。 enter image description here

我只是想获取输入字段的值,这样我就可以将值传递给动作创建者。

这是整个代码,

import React from 'react';
import { View, Text, TextInput, Button} from 'react-native';

class AddNewCategory extends React.Component {
  constructor(props) {
    super(props)
    this.state={
      text: ''
    };
    console.log('after initialising constructor');
    console.log(this.state);
    this.onContinueButtonPress = this.onContinueButtonPress.bind(this);
  }
  onContinueButtonPress() {
    console.log('after onContinueButtonPress');
    console.log(this.state);
    this.props.addNewCategory('Random Value');
  }
  render(){
    return(
      <View>
        <Text>Name your new task list</Text>
        <TextInput
          placeholder="Things to do today.."
          value={this.state.text}
          onChange={(text)=>this.setState({text: text})}
        />
        <Button
          title={'Continue'}
          onPress={this.onContinueButtonPress}
        />
      </View>
    );
  }
};

export default AddNewCategory;

1 个答案:

答案 0 :(得分:2)

我不知道为什么要给一个Button组件提供onChange道具。

无论如何,对于TextInput,您应该提供onChangeText属性。

<TextInput onChangeText={text => this.setState({ text })}

其他属性已被删除。

仅使用onChange就像在进行Web开发时处理通常的onChange事件一样,其中回调方法的第一个参数仅给出事件;要获得实际输入值,您必须说event.target.value

onChange={(event) => console.log(event.target.value)}