Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

282
Views
¿Cómo deslizar automáticamente la ventana desde detrás del teclado cuando TextInput tiene el foco?

He visto este truco para que las aplicaciones nativas se desplacen automáticamente por la ventana, pero me pregunto cuál es la mejor manera de hacerlo en React Native... Cuando un campo <TextInput> se enfoca y se coloca en la parte inferior de la vista, el teclado cubrirá el campo de texto.

Puede ver este problema en la vista TextInputExample.js de UIExplorer de ejemplo.

¿Alguien tiene una buena solución?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Respuesta 2017

KeyboardAvoidingView es probablemente la mejor manera de hacerlo ahora. Consulte los documentos aquí . Es realmente simple en comparación con el módulo de Keyboard , que le da al desarrollador más control para realizar animaciones. Spencer Carli demostró todas las formas posibles en su medio blog .

Respuesta 2015

La forma correcta de hacer esto en react-native no requiere bibliotecas externas, aprovecha el código nativo e incluye animaciones.

Primero defina una función que manejará el evento onFocus para cada TextInput (o cualquier otro componente al que le gustaría desplazarse):

 // Scroll a component into view. Just pass the component ref string. inputFocused (refName) { setTimeout(() => { let scrollResponder = this.refs.scrollView.getScrollResponder(); scrollResponder.scrollResponderScrollNativeHandleToKeyboard( React.findNodeHandle(this.refs[refName]), 110, //additionalOffset true ); }, 50); }

Luego, en su función de renderizado:

 render () { return ( <ScrollView ref='scrollView'> <TextInput ref='username' onFocus={this.inputFocused.bind(this, 'username')} </ScrollView> ) }

Esto usa RCTDeviceEventEmitter para eventos de teclado y dimensionamiento, mide la posición del componente usando RCTUIManager.measureLayout y calcula el movimiento de desplazamiento exacto requerido en scrollResponderInputMeasureAndScrollToKeyboard .

Es posible que desee experimentar con el parámetro additionalOffset Offset, para adaptarse a las necesidades de su diseño de interfaz de usuario específico.

over 4 years ago · Santiago Trujillo Report

0

KeyboardAvoidingView de código abierto de Facebook en react native 0.29 para resolver este problema. La documentación y el ejemplo de uso se pueden encontrar aquí .

over 4 years ago · Santiago Trujillo Report

0

Combinamos parte del código de forma react-native-keyboard-spacer y el código de @Sherlock para crear un componente KeyboardHandler que se puede envolver alrededor de cualquier vista con elementos TextInput. ¡Funciona de maravilla! :-)

 /** * Handle resizing enclosed View and scrolling to input * Usage: * <KeyboardHandler ref='kh' offset={50}> * <View> * ... * <TextInput ref='username' * onFocus={()=>this.refs.kh.inputFocused(this,'username')}/> * ... * </View> * </KeyboardHandler> * * offset is optional and defaults to 34 * Any other specified props will be passed on to ScrollView */ 'use strict'; var React=require('react-native'); var { ScrollView, View, DeviceEventEmitter, }=React; var myprops={ offset:34, } var KeyboardHandler=React.createClass({ propTypes:{ offset: React.PropTypes.number, }, getDefaultProps(){ return myprops; }, getInitialState(){ DeviceEventEmitter.addListener('keyboardDidShow',(frames)=>{ if (!frames.endCoordinates) return; this.setState({keyboardSpace: frames.endCoordinates.height}); }); DeviceEventEmitter.addListener('keyboardWillHide',(frames)=>{ this.setState({keyboardSpace:0}); }); this.scrollviewProps={ automaticallyAdjustContentInsets:true, scrollEventThrottle:200, }; // pass on any props we don't own to ScrollView Object.keys(this.props).filter((n)=>{return n!='children'}) .forEach((e)=>{if(!myprops[e])this.scrollviewProps[e]=this.props[e]}); return { keyboardSpace:0, }; }, render(){ return ( <ScrollView ref='scrollView' {...this.scrollviewProps}> {this.props.children} <View style={{height:this.state.keyboardSpace}}></View> </ScrollView> ); }, inputFocused(_this,refName){ setTimeout(()=>{ let scrollResponder=this.refs.scrollView.getScrollResponder(); scrollResponder.scrollResponderScrollNativeHandleToKeyboard( React.findNodeHandle(_this.refs[refName]), this.props.offset, //additionalOffset true ); }, 50); } }) // KeyboardHandler module.exports=KeyboardHandler;
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!