我可以解释我想要做什么,但是这个 ReactJS 示例正是我想要的。问题是我无法弄清楚反应原生的等效物是什么。
基本上,当我在 TextInput 中按回车键时,我希望清除文本并保持焦点。
有什么想法吗?
我可以解释我想要做什么,但是这个 ReactJS 示例正是我想要的。问题是我无法弄清楚反应原生的等效物是什么。
基本上,当我在 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 但如果你这样做并且它有效,你应该这样做。我发现在我正在制作的聊天应用程序中与功能性反应组件一起使用的另一件事是:
... 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/