我正在尝试在文本输入发生变化时更新它,但它似乎不起作用。
这是我的简化示例:
var Message = React.createClass({
getInitialState: function() {
return {textValue: ''};
},
render: function() {
return (
<View style={[styles.container]}>
<ProfilePicture userId={this.props.userId}/>
<TextInput
ref={component => this._textInput = component}
style={{flex: 8, paddingLeft: 5, fontSize: 15}}
onChangeText={this._handleChange}
//multiline={true}
defaultValue={""}
value={this.state.textValue}
returnKeyType={"send"}
blurOnSubmit={false}
autoFocus={true}
enablesReturnKeyAutomatically={true}
onSubmitEditing={this._onSubmit}
/>
</View>
);
},
_handleChange: function(text) {
this.setState({textValue: "foo"});
},
_onSubmit: function(event) {
this._clearText();
},
_clearText: function() {
this._textInput.setNativeProps({text: ''});
},
});
我希望一旦有人输入一些文本,它就会自动更改为“foo”,但这不起作用。
有什么想法吗?
更新
情节变厚了,
如果我为 onBlur
调用相同的函数,它会起作用,但仅当文本输入中没有文本时才会起作用。如果我更改函数以使用 this._textInput.setNativeProps({text: 'foo'});
而不是 this.setState({textValue: "foo"}); 设置值
然后它在文本输入为空和有数据时都有效。
例子:
render: function() {
return (
<TextInput
ref={component => this._textInput = component}
style={{flex: 8, paddingLeft: 5, fontSize: 15}}
onChangeText={this._handleChange}
onBlur={this._handleChange}
//multiline={true}
defaultValue={""}
value={this.state.textValue}
returnKeyType={"send"}
blurOnSubmit={false}
autoFocus={true}
enablesReturnKeyAutomatically={true}
onSubmitEditing={this._onSubmit}
/>
);
},
_handleChange: function(text) {
// what to do here check if there are youtube videos?
this._textInput.setNativeProps({text: 'foo'});
}
所以在上面 _handleChange 适用于 onBlur
但不适用于 onChangeText
。很奇怪吧?
最佳答案
这不是真正的最佳解决方案,但查看 react-native v 0.17.0 的 react native 代码,看起来在 onChange 期间对组件值所做的任何更改都不会生效。
HEAD 上的代码已更改,这可以修复它。 https://github.com/facebook/react-native/blob/master/Libraries/Components/TextInput/TextInput.js#L542
要解决这个问题,您可以像这样包装代码以在 setTimeout 中重置文本输入值
var self = this;
setTimeout(function() {self._textInput.setNativeProps({text: newText}); }, 1);
这会在当前更改事件之外创建一个新的更改。
就像我说的不是最佳解决方案,但它确实有效。
还有一个问题,如果新文本大于旧文本,则需要更新光标位置,这在 master 上尚不可用,但有一个 PR 看起来接近合并。 https://github.com/facebook/react-native/pull/2668
关于react-native - 如何在更改时更新文本输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34512006/