我可以解释我正在尝试做什么,但是这个ReactJS示例正好讲解了我想要的内容。问题是我无法弄清楚React Native的等效方法。
基本上,当我在TextInput中按返回键时,我希望文本被清除并保持焦点。
您有什么想法吗?
我可以解释我正在尝试做什么,但是这个ReactJS示例正好讲解了我想要的内容。问题是我无法弄清楚React Native的等效方法。
基本上,当我在TextInput中按返回键时,我希望文本被清除并保持焦点。
您有什么想法吗?
我已经提交了一个具有 blurOnSubmit
属性的 PR。
将其设置为 false
,则 TextInput
永远不会失焦,但是仍会触发 onSubmitEditing
。
希望能够被合并。:)
我想到了以下(有效)解决方案:
var NameInput = React.createClass({
getInitialState() {
return {
textValue: ''
}
},
clearAndRetainFocus: function(evt, elem) {
this.setState({textValue: elem.text});
setTimeout(function() {
this.setState({textValue: this.getInitialState().textValue});
this.refs.Name.focus();
}.bind(this), 0);
},
render() {
return(
<TextInput
ref='Name'
value={this.state.textValue}
onEndEditing={this.clearAndRetainFocus} />
)
}
});
所以,基本上当我们结束编辑时,我们会将textValue
状态设置为TextInput
的值,紧接着(在setTimeout
中),将其切换回默认值(空)并保持元素的焦点。
我不知道如何触发blurOnSubmit,但如果您知道并且它有效,您应该这样做。另一件事是,我发现在我制作的聊天应用程序中,使用功能性React组件可以实现以下效果:
... import statments
const ChatInput = props => {
const textIn = React.useRef(null) //declare ref
useEffect(()=>textIn.current.focus()) //use effect to focus after it is updated
const textInputChanged = (text) =>{
props.contentChanged(text);
}
const submitChat = () =>{
const txt = props.content.trim()
txt.length >0 ? props.sendChat(txt, props.username) : null;
}
const keyPressEvent = (e) =>{
return e.key == 'Enter'? submitChat() : null;
}
return (
<TextInput
style={styles.textInput}
keyboardType={props.keyboardType}
autoCapitalize={props.autoCapitalize}
autoCorrect={props.autoCorrect}
secureTextEntry={props.secureTextEntry}
value={props.content}
onChangeText={textInputChanged}
onKeyPress={keyPressEvent}
autoFocus={true} //i don't think you need this since we are using useEffect
ref={textIn} //make it so this is the ref
/>
)}
... export default react-redux connect stuff
如果你有更多的输入,你可以在useEffect钩子中做一些选择逻辑。
这篇文章帮助我弄清楚了,它几乎是相同的内容: https://howtocreateapps.com/how-to-set-focus-on-an-input-element-in-react-using-hooks/
onSubmitEditing
上怎么做呢? - Jarrod Mosen