【问题标题】:Set Focus to TextInput on TouchableHighlight onPress React Native在 TouchableHighlight onPress React Native 上将焦点设置为 TextInput
【发布时间】:2017-09-21 05:35:08
【问题描述】:

我正在尝试将焦点放在 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。

【问题讨论】:

  • 你在哪里调用你的 renderTotalAmountInModal 函数渲染?我在任何地方都看不到它
  • @AkshayRao 就在里面,因为render方法太长所以没加代码。

标签: react-native


【解决方案1】:

BTM 在 reactiflux #general chat 上提供了答案。

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

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

这解决了问题。

【讨论】:

    猜你喜欢
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 2018-05-10
    • 2018-07-11
    • 2020-06-06
    • 2016-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多