我试图在ReactNative中创建一个imagePicker,但是当我选择图像时,出现了错误:
TypeError:this.setState不是函数。 (在'this.setState({ 头像:data})','this.setState'未定义)
我不明白为什么现在我的状态不确定。
export default class ProfileEdit extends Component {
constructor(props) {
super(props);
async function getRoutedUser() {
const route = useRoute();
return route.params.user;
}
this.state = {
user: this.props.navigation.state.params.user,
avatar: ""
};
imagePickerCallback(data) {
this.setState({avatar: data})
}
...
<Button style={styleProperties.buttonEditProfImage} type="outline"
onPress={() => ImagePicker.showImagePicker({}, this.imagePickerCallback)}>
<Text style={styleProperties.buttonEditProfText}>Escolha uma imagem</Text>
</Button>
...
谢谢!
答案 0 :(得分:2)
您应该将imagePickerCallback
声明为箭头函数,或者将其绑定到构造函数中的函数。您可以在React here中阅读有关处理事件的更多信息。
尝试一下:
export default class ProfileEdit extends Component {
constructor(props) {
super(props);
async function getRoutedUser() {
const route = useRoute();
return route.params.user;
}
this.state = {
user: this.props.navigation.state.params.user,
avatar: ""
};
imagePickerCallback = (data) => {
this.setState({avatar: data})
}
...
<Button style={styleProperties.buttonEditProfImage} type="outline"
onPress={() => ImagePicker.showImagePicker({}, this.imagePickerCallback)}>
<Text style={styleProperties.buttonEditProfText}>Escolha uma imagem</Text>
</Button>
...
或尝试以下操作:
export default class ProfileEdit extends Component {
constructor(props) {
super(props);
async function getRoutedUser() {
const route = useRoute();
return route.params.user;
}
this.state = {
user: this.props.navigation.state.params.user,
avatar: ""
}
this.imagePickerCallback = this.imagePickerCallback.bind(this)
}
imagePickerCallback(data) {
this.setState({avatar: data})
}
...
<Button style={styleProperties.buttonEditProfImage} type="outline"
onPress={() => ImagePicker.showImagePicker({}, this.imagePickerCallback)}>
<Text style={styleProperties.buttonEditProfText}>Escolha uma imagem</Text>
</Button>
...