Ref轉(zhuǎn)發(fā)-具備更強(qiáng)的自定義組件能力

使用自定義組件(組合模式)時(shí),外層對(duì)原始組件的操作

CustomInput.tsx

import React, { useState, forwardRef } from 'react';
import {
  StyleSheet,
  View,
  Image,
  Text,
  TextInput,
  LayoutAnimation,
  TouchableOpacity,
} from 'react-native';

import icon_error from '../assets/images/icon_error.png';
import icon_right from '../assets/images/icon_right.png';
import icon_question from '../assets/images/icon_question.webp';
import icon_delete from '../assets/images/icon_delete.png';


export default forwardRef<any, TextInput>((props, ref) => {
    const [value, setValue] = useState<string>('');

    return (
        <View style={styles.root}>
            <View 
                style={[
                    styles.inputWrap, 
                    { borderColor: !value 
                        ? '#888' 
                        : value?.length === 11 
                            ? '#00CD00' 
                            : '#ff3050' }
                ]}>
                <TextInput
                    ref={ref}
                    style={styles.input}
                    value={value}
                    keyboardType='number-pad'
                    onChangeText={value => {
                        LayoutAnimation.spring();
                        setValue(value);
                    }}
                    maxLength={11}
                />

                {!!value &&
                    <TouchableOpacity
                        style={styles.deleteButton}
                        onPress={() => {
                            LayoutAnimation.spring();
                            setValue('');
                        }}
                    >
                        <Image style={styles.deleteImg} source={icon_delete} />
                    </TouchableOpacity>
                }
            </View>
            <View style={styles.tipsLayout}>
                {!value ?
                <>
                    <Image style={styles.tipImg} source={icon_question} />
                    <Text style={styles.tipsTxt}>請(qǐng)輸入您的手機(jī)號(hào)</Text>
                </> : value.length === 11 ?
                <>
                    <Image style={styles.tipImgRight} source={icon_right} />
                    <Text style={styles.tipsTxtRight}>輸入正確彰亥,可進(jìn)行提交</Text>
                </> :
                <>
                    <Image style={styles.tipImgError} source={icon_error} />
                    <Text style={styles.tipsTxtError}>格式錯(cuò)誤咧七,請(qǐng)輸入正確手機(jī)號(hào)</Text>
                </>}
            </View>
        </View>
    );
});

const styles = StyleSheet.create({
    root: {
        width: '100%',
        flexDirection: 'column',
    },
    input: {
        width: '100%',
        height: 56,
        backgroundColor: 'transparent',
        paddingHorizontal: 16,
        fontSize: 22,
        color: '#333',
    },
    inputWrap: {
        width: '100%',
        borderWidth: 2,
        borderRadius: 12,
        flexDirection: 'row',
        alignItems: 'center',
    },
    tipsLayout: {
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 6,
        paddingHorizontal: 6,
    },
    tipImg: {
        width: 22,
        height: 22,
        resizeMode: 'contain',
        tintColor: '#888',
    },
    tipsTxt: {
        fontSize: 15,
        color: '#666',
        marginLeft: 6,
        fontWeight: 'bold',
    },
    tipImgRight: {
        width: 18,
        height: 18,
        resizeMode: 'contain',
        tintColor: '#00CD00',
    },
    tipsTxtRight: {
        fontSize: 15,
        color: '#00CD00',
        marginLeft: 6,
        fontWeight: 'bold',
    },
    tipImgError: {
        width: 18,
        height: 18,
        resizeMode: 'contain',
        tintColor: '#ff3050',
    },
    tipsTxtError: {
        fontSize: 15,
        color: '#ff3050',
        marginLeft: 6,
        fontWeight: 'bold',
    },
    deleteButton: {
        position: 'absolute',
        right: 16,
    },
    deleteImg: {
        width: 24,
        height: 24,
        resizeMode: 'contain',
        borderRadius: 12,
    },
});

RefDemo.tsx

import React, { useRef } from 'react';
import {
  StyleSheet,
  View,
  Button,
  TextInput
} from 'react-native';

import CustomInput from './CustomInput';

export default () => {

    const inputRef = useRef<TextInput>(null);

    return (
        <View style={styles.root}>
            <Button title='聚焦' onPress={() => {
                inputRef.current?.focus();
            }} />
            <Button title='失焦' onPress={() => {
                inputRef.current?.blur();
            }} />
            <CustomInput ref={inputRef}/>
        </View>
    );
}

const styles = StyleSheet.create({
    root: {
        width: '100%',
        height: '100%',
        backgroundColor: 'white',
        paddingHorizontal: 20,
        paddingTop: 64,
    },
});

函數(shù)式組件對(duì)外暴露實(shí)例(通常是api)

CustomInput2.tsx

import React, { useState, useRef, forwardRef, useImperativeHandle } from 'react';
import {
  StyleSheet,
  View,
  Image,
  Text,
  TextInput,
  LayoutAnimation,
  TouchableOpacity,
} from 'react-native';

import icon_error from '../assets/images/icon_error.png';
import icon_right from '../assets/images/icon_right.png';
import icon_question from '../assets/images/icon_question.webp';
import icon_delete from '../assets/images/icon_delete.png';

export interface CustomInputRef2 {
    customFocus: () => void,
    customBlur: () => void,
}

export default forwardRef((props, ref) => {
    const inputRef = useRef<TextInput>(null);
    const [value, setValue] = useState<string>('');

    const customFocus = () => {
        console.log('customFocus...')
        inputRef.current?.focus();
    }

    const customBlur = () => {
        console.log('customBlur...')
        inputRef.current?.blur();
    }

    useImperativeHandle(ref, () => {
        return {
            customFocus,
            customBlur
        };
    })

    return (
        <View style={styles.root}>
            <View 
                style={[
                    styles.inputWrap, 
                    { borderColor: !value 
                        ? '#888' 
                        : value?.length === 11 
                            ? '#00CD00' 
                            : '#ff3050' }
                ]}>
                <TextInput
                    ref={inputRef}
                    style={styles.input}
                    value={value}
                    keyboardType='number-pad'
                    onChangeText={value => {
                        LayoutAnimation.spring();
                        setValue(value);
                    }}
                    maxLength={11}
                />

                {!!value &&
                    <TouchableOpacity
                        style={styles.deleteButton}
                        onPress={() => {
                            LayoutAnimation.spring();
                            setValue('');
                        }}
                    >
                        <Image style={styles.deleteImg} source={icon_delete} />
                    </TouchableOpacity>
                }
            </View>
            <View style={styles.tipsLayout}>
                {!value ?
                <>
                    <Image style={styles.tipImg} source={icon_question} />
                    <Text style={styles.tipsTxt}>請(qǐng)輸入您的手機(jī)號(hào)</Text>
                </> : value.length === 11 ?
                <>
                    <Image style={styles.tipImgRight} source={icon_right} />
                    <Text style={styles.tipsTxtRight}>輸入正確,可進(jìn)行提交</Text>
                </> :
                <>
                    <Image style={styles.tipImgError} source={icon_error} />
                    <Text style={styles.tipsTxtError}>格式錯(cuò)誤任斋,請(qǐng)輸入正確手機(jī)號(hào)</Text>
                </>}
            </View>
        </View>
    );
});

const styles = StyleSheet.create({
    root: {
        width: '100%',
        flexDirection: 'column',
    },
    input: {
        width: '100%',
        height: 56,
        backgroundColor: 'transparent',
        paddingHorizontal: 16,
        fontSize: 22,
        color: '#333',
    },
    inputWrap: {
        width: '100%',
        borderWidth: 2,
        borderRadius: 12,
        flexDirection: 'row',
        alignItems: 'center',
    },
    tipsLayout: {
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 6,
        paddingHorizontal: 6,
    },
    tipImg: {
        width: 22,
        height: 22,
        resizeMode: 'contain',
        tintColor: '#888',
    },
    tipsTxt: {
        fontSize: 15,
        color: '#666',
        marginLeft: 6,
        fontWeight: 'bold',
    },
    tipImgRight: {
        width: 18,
        height: 18,
        resizeMode: 'contain',
        tintColor: '#00CD00',
    },
    tipsTxtRight: {
        fontSize: 15,
        color: '#00CD00',
        marginLeft: 6,
        fontWeight: 'bold',
    },
    tipImgError: {
        width: 18,
        height: 18,
        resizeMode: 'contain',
        tintColor: '#ff3050',
    },
    tipsTxtError: {
        fontSize: 15,
        color: '#ff3050',
        marginLeft: 6,
        fontWeight: 'bold',
    },
    deleteButton: {
        position: 'absolute',
        right: 16,
    },
    deleteImg: {
        width: 24,
        height: 24,
        resizeMode: 'contain',
        borderRadius: 12,
    },
});

RefDemo2.tsx

import React, { useRef } from 'react';
import {
  StyleSheet,
  View,
  Button,
} from 'react-native';

import CustomInput2, {CustomInputRef2} from './CustomInput2';

export default () => {

    const inputRef = useRef<CustomInputRef2>(null);

    return (
        <View style={styles.root}>
            <Button title='聚焦' onPress={() => {
                inputRef.current?.customFocus();
            }} />
            <Button title='失焦' onPress={() => {
                inputRef.current?.customBlur();
            }} />
            <CustomInput2 ref={inputRef} />
        </View>
    );
}

const styles = StyleSheet.create({
    root: {
        width: '100%',
        height: '100%',
        backgroundColor: 'white',
        paddingHorizontal: 20,
        paddingTop: 64,
    },
});

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末继阻,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子废酷,更是在濱河造成了極大的恐慌瘟檩,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,755評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件澈蟆,死亡現(xiàn)場(chǎng)離奇詭異墨辛,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)趴俘,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門睹簇,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人寥闪,你說(shuō)我怎么就攤上這事太惠。” “怎么了疲憋?”我有些...
    開封第一講書人閱讀 165,138評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵凿渊,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我缚柳,道長(zhǎng)埃脏,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,791評(píng)論 1 295
  • 正文 為了忘掉前任秋忙,我火速辦了婚禮彩掐,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘灰追。我一直安慰自己佩谷,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,794評(píng)論 6 392
  • 文/花漫 我一把揭開白布监嗜。 她就那樣靜靜地躺著谐檀,像睡著了一般。 火紅的嫁衣襯著肌膚如雪裁奇。 梳的紋絲不亂的頭發(fā)上桐猬,一...
    開封第一講書人閱讀 51,631評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音刽肠,去河邊找鬼溃肪。 笑死免胃,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的惫撰。 我是一名探鬼主播羔沙,決...
    沈念sama閱讀 40,362評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼厨钻!你這毒婦竟也來(lái)了扼雏?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,264評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤夯膀,失蹤者是張志新(化名)和其女友劉穎诗充,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體诱建,經(jīng)...
    沈念sama閱讀 45,724評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡蝴蜓,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了俺猿。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片茎匠。...
    茶點(diǎn)故事閱讀 40,040評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡譬胎,死狀恐怖秉撇,靈堂內(nèi)的尸體忽然破棺而出祝谚,到底是詐尸還是另有隱情翰守,我是刑警寧澤,帶...
    沈念sama閱讀 35,742評(píng)論 5 346
  • 正文 年R本政府宣布剥啤,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏午笛。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,364評(píng)論 3 330
  • 文/蒙蒙 一苗桂、第九天 我趴在偏房一處隱蔽的房頂上張望药磺。 院中可真熱鬧,春花似錦煤伟、人聲如沸癌佩。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)围辙。三九已至,卻和暖如春放案,著一層夾襖步出監(jiān)牢的瞬間姚建,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工吱殉, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留掸冤,地道東北人厘托。 一個(gè)月前我還...
    沈念sama閱讀 48,247評(píng)論 3 371
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像稿湿,于是被迫代替她去往敵國(guó)和親铅匹。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,979評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容