将文字输入聚焦在TouchableHighlight上

时间:2018-07-03 06:14:38

标签: javascript react-native

我有一堂课,我希望其中的文本输入能专注于被选中的父级。

class ListItem extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {
           editable: this.props.item.editable,
           value: this.props.item.value,
           heading: this.props.item.heading,
           item: this.props.item.item,
        }
    }

    _onPress = () => {
        this.setState({ editable: true});
        this.props.onPressItem(this.props.index, this.props, this.state);
    }

    _onSearchTextChanged = (event) => {
        this.setState({ value: event.nativeEvent.text });
      };

    _handleSaveEvent = (e) => {
        this.setState({ editable: false });
        alert('works');
        //Add in saving item
    }

    render() {
      var editable = this.state.editable;
      var heading = this.state.heading;
      var value = this.state.value;
      return (
        <TouchableHighlight onPress={this._onPress} underlayColor='#dddddd'>
          <View>
            <View style={styles.rowContainer}>
              <View style={styles.textContainer}>
                <Text style={styles.title}>{heading}: </Text>
                {this.state.editable? 
                    <TextInput
                        style={styles.searchInput}
                        value={value.toString()}
                        onChange={this._onSearchTextChanged}
                        keyboardType="default"
                        returnKeyType="done"
                        onSubmitEditing={this._handleSaveEvent}/>
                : 
                    <Text style={styles.price}>{value}</Text> 
                }
                {}
              </View>
            </View>
            <View style={styles.separator}/>
          </View>
        </TouchableHighlight>
      );
    }
  }

我尝试添加

  

autoFocus = {true}

我也尝试添加

  

ref = {this.props.index}

但是当我尝试关注它时,它告诉我它未定义(this.refs [this.props.index] .focus();)

我希望在启用“可编辑”状态时将其重点关注,但我不确定为什么这看起来如此困难。我的背景更多地是在C#,Angular 2+等中,所以也许它的反应结构如何使我失望

2 个答案:

答案 0 :(得分:1)

onPress setState TouchableHighlight的{​​{1}}事件上并在TextInput中设置editable: true。它将起作用

autoFocus={this.state.editable}

答案 1 :(得分:0)

您可以尝试一下。像这样在<TextInput />中提供ref作为函数:

<TextInput
        ref ={ref => this.inputText = ref}
        style={styles.searchInput}
        keyboardType="default"
        placeholder="Type anything"
        returnKeyType="done"/>

现在在<Button /> onPress上,像这样聚焦<TextInput />

<TouchableHighlight onPress={() => this.inputText.focus()}> 
    <Text>Click</Text>
</TouchableHightlight>

这应该有效。让我知道是否有问题。

相关问题