[英]React Native - TextInput.setNativeProps isn't triggering onChange
I am trying to clear a text input using setNativeProps({ text: '' })
which according to the documentation is a common way to do so -- due to the flickering of state changes -- However, I did notice that onChange
is not called when setNativeProps
is called. 我正在尝试使用setNativeProps({ text: '' })
清除文本输入,根据文档,这是一种常见的处理方式-由于状态更改的闪烁-但是,我确实注意到onChange
不是在调用setNativeProps
调用。 For me, this is an issue because I am using a resizable TextArea. 对我来说,这是个问题,因为我正在使用可调整大小的TextArea。 I need the TextArea to reset its height, which is currently done onChange
. 我需要TextArea重置其高度,当前已完成onChange
。
If someone can help shed light on my issue it would be much appreciated. 如果有人可以帮助阐明我的问题,将不胜感激。
Here is the component 这是组件
import React, { Component } from 'react';
import {
TextInput,
} from 'react-native';
export default class Input extends Component {
constructor() {
super();
this.state = {
height: 35,
};
this.handleChange = this.handleChange.bind(this);
}
componentWillMount() {
const { defaultHeight } = this.props;
if (defaultHeight) {
this.setState({
height: defaultHeight,
});
}
}
handleChange(event) {
console.log(event);
if (this.state.height !== event.nativeEvent.contentSize.height) {
this.setState({
height: Math.max(this.props.defaultHeight, event.nativeEvent.contentSize.height),
});
}
if (this.props.onChange) {
this.props.onChange(event);
}
}
render() {
const { style, ...props } = this.props;
return (
<TextInput
ref="input"
style={[{ height:this.state.height }, style]}
multiline
{...props}
onChange={this.handleChange}
/>);
}
}
Input.propTypes = {
style: React.PropTypes.number,
onChange: React.PropTypes.func,
defaultHeight: React.PropTypes.number,
};
From my other component, I am doing the following to clear the input 从我的其他组件中,我正在执行以下操作以清除输入
this.refs.input.refs.input.setNativeProps({ text: '' });
I still haven't found a way for onChange to still be called, but i did find a solution. 我仍然没有找到仍可以调用onChange的方法,但是我确实找到了解决方案。
The solution was to create another function that will call setNativeProps and reset the state 解决方案是创建另一个函数,该函数将调用setNativeProps并重置状态
resetInputText() {
this.refs.input.setNativeProps({ text: '' });
this.setState({
height: this.props.defaultHeight,
});
}
From my other component I could then call this.refs.input.resetInputText();
然后从其他组件中调用this.refs.input.resetInputText();
and see the desired result. 并看到所需的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.