TypeScript & RN & refs使用

方式一:

export default class InputView extends React.Component<any,any>{
    refs:{
        [key: string]: (any);
        input:RN.TextInput;
    }
    constructor(props:any)
    {
        super(props);
    }

    private _onClick():void{
        let v = this.refs["input"];
        v.clear();
        ToastAndroid.show(v +"  ",ToastAndroid.LONG);
    }

    render()
    {
        return(
            <View style={styles.container}>
                <TextInput ref="input" placeholder="请输入内容" style={{width:200}}/>
                <View style={{borderWidth:1,borderColor:'red'}}>
                    <Text style={styles.btn} onPress={this._onClick.bind(this)}>ADD</Text>
                </View>
            </View>
        );
    }
}

方式二:

interface IRefKey{
    input?:React.TextInput;
}
export default class InputView extends React.Component<any,any>{
    refKey : IRefKey = {};
    constructor(props:any)
    {
        super(props);
    }

    private _onClick():void{
        this.refKey.input.clear();
    }

    render()
    {
        return(
            <View style={styles.container}>
                <TextInput ref={(ref:any)=> this.refKey.input = ref} placeholder="请输入内容" style={{width:200}}/>
                <View style={{borderWidth:1,borderColor:'red'}}>
                    <Text style={styles.btn} onPress={this._onClick.bind(this)}>ADD</Text>
                </View>
            </View>
        );
    }
}

参考:
How to use refs in react with Typescript

stackoverflow

TextInput

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容