在TouchableHighlight onPress React Native上将焦点设置为TextInput

时间:2017-09-21 05:35:09

标签: react-native

我正在尝试将焦点放在TouchableHighlight onPress方法上的TextInput上。但这给了我以下错误。

  

undefined不是一个对象(评估   this.refs.TotalInputField.focus')

我的代码如下。

setCustomTotalAmount(value) {
        LayoutAnimation.easeInEaseOut();
        this.setState({
            customTextValue: true
        });
        this.refs.TotalInputField.focus();
},

renderTotalAmountInModal() {
        if (this.state.customTextValue) {
            return (
                <TextInput
                    style={styles.totalTextInput}
                    ref='TotalInputField'
                    returnKeyType='done'
                    onChangeText={(totalAmount) => this.setCustomTotalValue(totalAmount)}
                    keyboardType='numeric'
                    defaultValue={this.state.totalAmount}
                />
            );
        } else {
            return (
                <Text style={styles.totalAreaText}>{this.props.symbol}{(this.state.totalAmount).toFixed(2)}</Text>
            );
        }
},

render(){
    return(
            <TouchableHighlight underlayColor="rgba(0,0,0,0)"
                                style={styles.customTotalButtonBorder}
                                onPress={this.setCustomTotalAmount.bind(this, true)}>
                <Text style={styles.buttonBorderText}>Set a custom total/Text>
            </TouchableHighlight>
    )
},

如何正确处理? TIA。

1 个答案:

答案 0 :(得分:0)

答案由BTM提供有关reactiflux #general chat的信息。

问题是在调用ref时组件没有正确安装。

componentDidUpdate(prevProps, prevState) {
  if(prevState.customTextValue === false && this.state.customTextValue === true) {
    this.refs.TotalInputField.focus();
  }
}

这解决了这个问题。

相关问题