如何从自定义组件的输入中获取文本

How to get text from custom component's input

我需要从自定义组件获取数据到屏幕。首先我将数据传递给这个组件:

<SearchInputComponent dataFromParent={this.state.text} />

这是我的组件的代码:

class SearchInputComponent extends Component {
  clearText = () => {
    this._textInput.setNativeProps({ text: '' });
  };

  render() {
    return (
      <View style={{ flex: 1, flexDirection: 'row' }}>
        <Input
          ref={component => this._textInput = component}
          placeholder="Enter city"
          value={this.props.dataFromParent}
        />
        <Button
          buttonStyle={{ width: 40, height: 40, backgroundColor: 'red' }}
          onPress={this.clearText}
          icon={(
            <MaterialIcons
              name="delete"
              size={30}
              color="black"
            />
          )}
        />
      </View>
    );
  }
}

export default SearchInputComponent;

据我了解,数据是从状态传递的,如果我在组件中更改它,它的状态也会更改。或者也许我错了?但是当我尝试输入文本到该组件的输入时,它会立即清除。我需要在点击按钮后获取文本(例如屏幕中的这种方法):

onPressSearch = () => {
      Alert.alert(this.state.cityName);
    };

那么,你能帮我吗?

UPD

class SearchInputComponent extends Component {
  clearText = () => {
    this._textInput.setNativeProps({ text: '' });
  };

  render() {
    return (
      <View style={{ flex: 1, flexDirection: 'row' }}>
        <Input
          ref={component => this._textInput = component}
          placeholder="Enter city"
          onChangeText={this.props.onInputChange}
          value={this.props.dataFromParent}
        />
        <Button
          buttonStyle={{ width: 40, height: 40, backgroundColor: 'red' }}
          onPress={this.clearText}
          icon={(
            <MaterialIcons
              name="delete"
              size={30}
              color="black"
            />
          )}
        />
      </View>
    );
  }
}

export default SearchInputComponent;

你应该给你的 SearchInputComponent 组件添加一个新的 prop,例如调用它 onInputChange,这个 prop 将接受一个函数。然后你将这个道具传递给你的 <input/> 组件,就像你对 dataFromParent.

所做的一样

组件:

class SearchInputComponent extends Component {
  ...
  render() {
    return (
      <Input
        onChangeText={this.props.onInputChange}
        ...
      />
      <Button
        onPress={this.props.onClearPress}
        ...
      />
      ...
    );
  }
}

家长:

<SearchInputComponent
  dataFromParent={this.state.value}
  onInputChange={value => this.setState({ value })}
  onClearPress={() => this.setState({ value: '' })}
/>

现在您可以像这样从父状态访问输入值 this.state.value

编辑: 不建议使用 ref 来获取或更新 <Input /> 的值(我假设您来自本地 Android/iOS 开发,我们从视图中获取引用并直接更新它).相反,您应该像这样 this.setState({ value: "" }); 清除 dataFromParent,这将自动清除您的 <Input />。我更新了上面的代码。