TextInput - React Native

文章推薦指數: 80 %
投票人數:10人

... and different keyboard types, such as a numeric keypad. ... Note that on Android performing text selection in an input can change the ... SkiptomaincontentReactNative0.66Next0.660.650.640.630.620.610.60AllversionsDocsComponentsAPICommunityBlog🌜🌞SearchOnthispageAfoundationalcomponentforinputtingtextintotheappviaakeyboard.Propsprovideconfigurabilityforseveralfeatures,suchasauto-correction,auto-capitalization,placeholdertext,anddifferentkeyboardtypes,suchasanumerickeypad.ThemostbasicusecaseistoplopdownaTextInputandsubscribetotheonChangeTexteventstoreadtheuserinput.Therearealsootherevents,suchasonSubmitEditingandonFocusthatcanbesubscribedto.Aminimalexample:Twomethodsexposedviathenativeelementare.focus()and.blur()thatwillfocusorblurtheTextInputprogrammatically.Notethatsomepropsareonlyavailablewithmultiline={true/false}.Additionally,borderstylesthatapplytoonlyonesideoftheelement(e.g.,borderBottomColor,borderLeftWidth,etc.)willnotbeappliedifmultiline=true.Toachievethesameeffect,youcanwrapyourTextInputinaView:TextInputhasbydefaultaborderatthebottomofitsview.Thisborderhasitspaddingsetbythebackgroundimageprovidedbythesystem,anditcannotbechanged.Solutionstoavoidthisaretoeithernotsetheightexplicitly,inwhichcasethesystemwilltakecareofdisplayingtheborderinthecorrectposition,ortonotdisplaytheborderbysettingunderlineColorAndroidtotransparent.NotethatonAndroidperformingtextselectioninaninputcanchangetheapp'sactivitywindowSoftInputModeparamtoadjustResize.Thismaycauseissueswithcomponentsthathaveposition:'absolute'whilethekeyboardisactive.ToavoidthisbehavioreitherspecifywindowSoftInputModeinAndroidManifest.xml(https://developer.android.com/guide/topics/manifest/activity-element.html)orcontrolthisparamprogrammaticallywithnativecode.Props​ViewProps​InheritsViewProps.allowFontScaling​SpecifieswhetherfontsshouldscaletorespectTextSizeaccessibilitysettings.Thedefaultistrue.TypeboolautoCapitalize​TellsTextInputtoautomaticallycapitalizecertaincharacters.Thispropertyisnotsupportedbysomekeyboardtypessuchasname-phone-pad.characters:allcharacters.words:firstletterofeachword.sentences:firstletterofeachsentence(default).none:don'tautocapitalizeanything.Typeenum('none','sentences','words','characters')autoCompleteAndroid​Specifiesautocompletehintsforthesystem,soitcanprovideautofill.OnAndroid,thesystemwillalwaysattempttoofferautofillbyusingheuristicstoidentifythetypeofcontent.Todisableautocomplete,setautoCompletetooff.PossiblevaluesforautoCompleteare:birthdate-daybirthdate-fullbirthdate-monthbirthdate-yearcc-csccc-expcc-exp-daycc-exp-monthcc-exp-yearcc-numberemailgendernamename-familyname-givenname-middlename-middle-initialname-prefixname-suffixpasswordpassword-newpostal-addresspostal-address-countrypostal-address-extendedpostal-address-extended-postal-codepostal-address-localitypostal-address-regionpostal-codestreet-addresssms-otpteltel-country-codetel-nationaltel-deviceusernameusername-newoffTypeenum('birthdate-day','birthdate-full','birthdate-month','birthdate-year','cc-csc','cc-exp','cc-exp-day','cc-exp-month','cc-exp-year','cc-number','email','gender','name','name-family','name-given','name-middle','name-middle-initial','name-prefix','name-suffix','password','password-new','postal-address','postal-address-country','postal-address-extended','postal-address-extended-postal-code','postal-address-locality','postal-address-region','postal-code','street-address','sms-otp','tel','tel-country-code','tel-national','tel-device','username','username-new','off')autoCorrect​Iffalse,disablesauto-correct.Thedefaultvalueistrue.TypeboolautoFocus​Iftrue,focusestheinputoncomponentDidMountoruseEffect.Thedefaultvalueisfalse.TypeboolblurOnSubmit​Iftrue,thetextfieldwillblurwhensubmitted.Thedefaultvalueistrueforsingle-linefieldsandfalseformultilinefields.Notethatformultilinefields,settingblurOnSubmittotruemeansthatpressingreturnwillblurthefieldandtriggertheonSubmitEditingeventinsteadofinsertinganewlineintothefield.TypeboolcaretHidden​Iftrue,caretishidden.Thedefaultvalueisfalse.TypeboolclearButtonModeiOS​Whentheclearbuttonshouldappearontherightsideofthetextview.Thispropertyissupportedonlyforsingle-lineTextInputcomponent.Thedefaultvalueisnever.Typeenum('never','while-editing','unless-editing','always')clearTextOnFocusiOS​Iftrue,clearsthetextfieldautomaticallywheneditingbegins.TypeboolcontextMenuHidden​Iftrue,contextmenuishidden.Thedefaultvalueisfalse.TypebooldataDetectorTypesiOS​DeterminesthetypesofdataconvertedtoclickableURLsinthetextinput.Onlyvalidifmultiline={true}andeditable={false}.Bydefaultnodatatypesaredetected.Youcanprovideonetypeoranarrayofmanytypes.PossiblevaluesfordataDetectorTypesare:'phoneNumber''link''address''calendarEvent''none''all'Typeenum('phoneNumber','link','address','calendarEvent','none','all'),,arrayofenum('phoneNumber','link','address','calendarEvent','none','all')defaultValue​Providesaninitialvaluethatwillchangewhentheuserstartstyping.Usefulforuse-caseswhereyoudonotwanttodealwithlisteningtoeventsandupdatingthevalueproptokeepthecontrolledstateinsync.TypestringdisableFullscreenUIAndroid​Whenfalse,ifthereisasmallamountofspaceavailablearoundatextinput(e.g.landscapeorientationonaphone),theOSmaychoosetohavetheusereditthetextinsideofafullscreentextinputmode.Whentrue,thisfeatureisdisabledanduserswillalwayseditthetextdirectlyinsideofthetextinput.Defaultstofalse.Typebooleditable​Iffalse,textisnoteditable.Thedefaultvalueistrue.TypeboolenablesReturnKeyAutomaticallyiOS​Iftrue,thekeyboarddisablesthereturnkeywhenthereisnotextandautomaticallyenablesitwhenthereistext.Thedefaultvalueisfalse.TypeboolimportantForAutofillAndroid​TellstheoperatingsystemwhethertheindividualfieldsinyourappshouldbeincludedinaviewstructureforautofillpurposesonAndroidAPILevel26+.Possiblevaluesareauto,no,noExcludeDescendants,yes,andyesExcludeDescendants.Thedefaultvalueisauto.auto:LettheAndroidSystemuseitsheuristicstodetermineiftheviewisimportantforautofill.no:Thisviewisn'timportantforautofill.noExcludeDescendants:Thisviewanditschildrenaren'timportantforautofill.yes:Thisviewisimportantforautofill.yesExcludeDescendants:Thisviewisimportantforautofill,butitschildrenaren'timportantforautofill.Typeenum('auto','no','noExcludeDescendants','yes','yesExcludeDescendants')inlineImageLeftAndroid​Ifdefined,theprovidedimageresourcewillberenderedontheleft.Theimageresourcemustbeinside/android/app/src/main/res/drawableandreferencedlikeCopyTypestringinlineImagePaddingAndroid​Paddingbetweentheinlineimage,ifany,andthetextinputitself.TypenumberinputAccessoryViewIDiOS​AnoptionalidentifierwhichlinksacustomInputAccessoryViewtothistextinput.TheInputAccessoryViewisrenderedabovethekeyboardwhenthistextinputisfocused.TypestringkeyboardAppearanceiOS​Determinesthecolorofthekeyboard.Typeenum('default','light','dark')keyboardType​Determineswhichkeyboardtoopen,e.g.numeric.Seescreenshotsofallthetypeshere.Thefollowingvaluesworkacrossplatforms:defaultnumber-paddecimal-padnumericemail-addressphone-padiOSOnlyThefollowingvaluesworkoniOSonly:ascii-capablenumbers-and-punctuationurlname-phone-padtwitterweb-searchAndroidOnlyThefollowingvaluesworkonAndroidonly:visible-passwordTypeenum('default','email-address','numeric','phone-pad','ascii-capable','numbers-and-punctuation','url','number-pad','name-phone-pad','decimal-pad','twitter','web-search','visible-password')maxFontSizeMultiplier​SpecifieslargestpossiblescaleafontcanreachwhenallowFontScalingisenabled.Possiblevalues:null/undefined(default):inheritfromtheparentnodeortheglobaldefault(0)0:nomax,ignoreparent/globaldefault>=1:setsthemaxFontSizeMultiplierofthisnodetothisvalueTypenumbermaxLength​Limitsthemaximumnumberofcharactersthatcanbeentered.UsethisinsteadofimplementingthelogicinJStoavoidflicker.Typenumbermultiline​Iftrue,thetextinputcanbemultiplelines.Thedefaultvalueisfalse.ItisimportanttonotethatthisalignsthetexttothetoponiOS,andcentersitonAndroid.UsewithtextAlignVerticalsettotopforthesamebehaviorinbothplatforms.TypeboolnumberOfLinesAndroid​SetsthenumberoflinesforaTextInput.Useitwithmultilinesettotruetobeabletofillthelines.TypenumberonBlur​Callbackthatiscalledwhenthetextinputisblurred.Note:IfyouareattemptingtoaccessthetextvaluefromnativeEventkeepinmindthattheresultingvalueyougetcanbeundefinedwhichcancauseunintendederrors.IfyouaretryingtofindthelastvalueofTextInput,youcanusetheonEndEditingevent,whichisfireduponcompletionofediting.TypefunctiononChange​Callbackthatiscalledwhenthetextinput'stextchanges.Type({nativeEvent:{eventCount,target,text}})=>voidonChangeText​Callbackthatiscalledwhenthetextinput'stextchanges.Changedtextispassedasasinglestringargumenttothecallbackhandler.TypefunctiononContentSizeChange​Callbackthatiscalledwhenthetextinput'scontentsizechanges.Onlycalledformultilinetextinputs.Type({nativeEvent:{contentSize:{width,height}}})=>voidonEndEditing​Callbackthatiscalledwhentextinputends.TypefunctiononPressIn​Callbackthatiscalledwhenatouchisengaged.Type({nativeEvent:PressEvent})=>voidonPressOut​Callbackthatiscalledwhenatouchisreleased.Type({nativeEvent:PressEvent})=>voidonFocus​Callbackthatiscalledwhenthetextinputisfocused.Type({nativeEvent:LayoutEvent})=>voidonKeyPress​Callbackthatiscalledwhenakeyispressed.ThiswillbecalledwithobjectwherekeyValueis'Enter'or'Backspace'forrespectivekeysandthetyped-incharacterotherwiseincluding''forspace.FiresbeforeonChangecallbacks.Note:onAndroidonlytheinputsfromsoftkeyboardarehandled,notthehardwarekeyboardinputs.Type({nativeEvent:{key:keyValue}})=>voidonLayout​Invokedonmountandonlayoutchanges.Type({nativeEvent:LayoutEvent})=>voidonScroll​Invokedoncontentscroll.MayalsocontainotherpropertiesfromScrollEventbutonAndroidcontentSizeisnotprovidedforperformancereasons.Type({nativeEvent:{contentOffset:{x,y}}})=>voidonSelectionChange​Callbackthatiscalledwhenthetextinputselectionischanged.Type({nativeEvent:{selection:{start,end}}})=>voidonSubmitEditing​Callbackthatiscalledwhenthetextinput'ssubmitbuttonispressed.Type({nativeEvent:{text,eventCount,target}})=>voidNotethatoniOSthismethodisn'tcalledwhenusingkeyboardType="phone-pad".placeholder​Thestringthatwillberenderedbeforetextinputhasbeenentered.TypestringplaceholderTextColor​Thetextcoloroftheplaceholderstring.TypecolorreturnKeyLabelAndroid​Setsthereturnkeytothelabel.UseitinsteadofreturnKeyType.TypestringreturnKeyType​Determineshowthereturnkeyshouldlook.OnAndroidyoucanalsousereturnKeyLabel.CrossplatformThefollowingvaluesworkacrossplatforms:donegonextsearchsendAndroidOnlyThefollowingvaluesworkonAndroidonly:nonepreviousiOSOnlyThefollowingvaluesworkoniOSonly:defaultemergency-callgooglejoinrouteyahooTypeenum('done','go','next','search','send','none','previous','default','emergency-call','google','join','route','yahoo')rejectResponderTerminationiOS​Iftrue,allowsTextInputtopasstoucheventstotheparentcomponent.ThisallowscomponentssuchasSwipeableListViewtobeswipeablefromtheTextInputoniOS,asisthecaseonAndroidbydefault.Iffalse,TextInputalwaysaskstohandletheinput(exceptwhendisabled).Thedefaultvalueistrue.TypeboolscrollEnablediOS​Iffalse,scrollingofthetextviewwillbedisabled.Thedefaultvalueistrue.Onlyworkswithmultiline={true}.TypeboolsecureTextEntry​Iftrue,thetextinputobscuresthetextenteredsothatsensitivetextlikepasswordsstaysecure.Thedefaultvalueisfalse.Doesnotworkwithmultiline={true}.Typeboolselection​Thestartandendofthetextinput'sselection.Setstartandendtothesamevaluetopositionthecursor.Typeobject:{start:number,end:number}selectionColor​Thehighlightandcursorcolorofthetextinput.TypecolorselectTextOnFocus​Iftrue,alltextwillautomaticallybeselectedonfocus.TypeboolshowSoftInputOnFocus​Whenfalse,itwillpreventthesoftkeyboardfromshowingwhenthefieldisfocused.Thedefaultvalueistrue.TypeboolspellCheckiOS​Iffalse,disablesspell-checkstyle(i.e.redunderlines).ThedefaultvalueisinheritedfromautoCorrect.TypebooltextAlign​Aligntheinputtexttotheleft,center,orrightsidesoftheinputfield.PossiblevaluesfortextAlignare:leftcenterrightTypeenum('left','center','right')textContentTypeiOS​Givethekeyboardandthesysteminformationabouttheexpectedsemanticmeaningforthecontentthatusersenter.ForiOS11+youcansettextContentTypetousernameorpasswordtoenableautofilloflogindetailsfromthedevicekeychain.ForiOS12+newPasswordcanbeusedtoindicateanewpasswordinputtheusermaywanttosaveinthekeychain,andoneTimeCodecanbeusedtoindicatethatafieldcanbeautofilledbyacodearrivinginanSMS.Todisableautofill,settextContentTypetonone.PossiblevaluesfortextContentTypeare:noneURLaddressCityaddressCityAndStateaddressStatecountryNamecreditCardNumberemailAddressfamilyNamefullStreetAddressgivenNamejobTitlelocationmiddleNamenamenamePrefixnameSuffixnicknameorganizationNamepostalCodestreetAddressLine1streetAddressLine2sublocalitytelephoneNumberusernamepasswordnewPasswordoneTimeCodeTypeenum('none','URL','addressCity','addressCityAndState','addressState','countryName','creditCardNumber','emailAddress','familyName','fullStreetAddress','givenName','jobTitle','location','middleName','name','namePrefix','nameSuffix','nickname','organizationName','postalCode','streetAddressLine1','streetAddressLine2','sublocality','telephoneNumber','username','password')passwordRulesiOS​WhenusingtextContentTypeasnewPasswordoniOSwecanlettheOSknowtheminimumrequirementsofthepasswordsothatitcangenerateonethatwillsatisfythem.InordertocreateavalidstringforPasswordRulestakealooktotheAppleDocs.Ifpasswordsgenerationdialogdoesn'tappearpleasemakesurethat:AutoFillisenabled:Settings→Passwords&Accounts→toggle"On"theAutoFillPasswords,iCloudKeychainisused:Settings→AppleID→iCloud→Keychain→toggle"On"theiCloudKeychain.Typestringstyle​NotethatnotallTextstylesaresupported,anincompletelistofwhatisnotsupportedincludes:borderLeftWidthborderTopWidthborderRightWidthborderBottomWidthborderTopLeftRadiusborderTopRightRadiusborderBottomRightRadiusborderBottomLeftRadiusseeIssue#7070formoredetail.StylesTypeTexttextBreakStrategyAndroid​SettextbreakstrategyonAndroidAPILevel23+,possiblevaluesaresimple,highQuality,balancedThedefaultvalueissimple.Typeenum('simple','highQuality','balanced')underlineColorAndroidAndroid​ThecoloroftheTextInputunderline.Typecolorvalue​Thevaluetoshowforthetextinput.TextInputisacontrolledcomponent,whichmeansthenativevaluewillbeforcedtomatchthisvaluepropifprovided.Formostuses,thisworksgreat,butinsomecasesthismaycauseflickering-onecommoncauseispreventingeditsbykeepingvaluethesame.Inadditiontosettingthesamevalue,eitherseteditable={false},orset/updatemaxLengthtopreventunwantededitswithoutflicker.TypestringMethods​.focus()​focus();CopyMakesthenativeinputrequestfocus..blur()​blur();CopyMakesthenativeinputlosefocus.clear()​clear();CopyRemovesalltextfromtheTextInput.isFocused()​isFocused();CopyReturnstrueiftheinputiscurrentlyfocused;falseotherwise.react-native#19096:Doesn'tsupportAndroid'sonKeyPreIme.react-native#19366:Calling.focus()afterclosingAndroid'skeyboardviabackbuttondoesn'tbringkeyboardupagain.react-native#26799:Doesn'tsupportAndroid'ssecureTextEntrywhenkeyboardType="email-address"orkeyboardType="phone-pad".Previous«TextNextTouchableHighlight»PropsViewPropsallowFontScalingautoCapitalizeautoCompleteAndroidautoCorrectautoFocusblurOnSubmitcaretHiddenclearButtonModeiOSclearTextOnFocusiOScontextMenuHiddendataDetectorTypesiOSdefaultValuedisableFullscreenUIAndroideditableenablesReturnKeyAutomaticallyiOSimportantForAutofillAndroidinlineImageLeftAndroidinlineImagePaddingAndroidinputAccessoryViewIDiOSkeyboardAppearanceiOSkeyboardTypemaxFontSizeMultipliermaxLengthmultilinenumberOfLinesAndroidonBluronChangeonChangeTextonContentSizeChangeonEndEditingonPressInonPressOutonFocusonKeyPressonLayoutonScrollonSelectionChangeonSubmitEditingplaceholderplaceholderTextColorreturnKeyLabelAndroidreturnKeyTyperejectResponderTerminationiOSscrollEnablediOSsecureTextEntryselectionselectionColorselectTextOnFocusshowSoftInputOnFocusspellCheckiOStextAligntextContentTypeiOSpasswordRulesiOSstyletextBreakStrategyAndroidunderlineColorAndroidAndroidvalueMethods.focus().blur()clear()isFocused()



請為這篇文章評分?