这是一个非常奇怪的问题,我确信我忽略了一些非常简单的事情。
当我加载新组件AddNewCategory
时,我最初将一个空字符串设置为text
上的this.state
属性。登录控制台也会将text
值显示为空。
我使用onChange
组件的Button
更新此值。我知道text
属性到目前为止已按预期更新,因为输入字段的值会相应更改。
<Button onChange={text=>this.setState({})}>
但是当我尝试检索text
属性的值时,我发现text
不是字符串而是分配了Proxy
对象。
我只是想获取输入字段的值,这样我就可以将值传递给动作创建者。
这是整个代码,
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;
答案 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)}