我爱编程

TypeScript & RN & refs使用

2016-09-07  本文已影响898人  lyzaijs

方式一:

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

上一篇 下一篇

猜你喜欢

热点阅读