如何在 React Native 中从 child 视图获取道具

How to get props from a child view in react native

我有一个 react-native 这样的观点。

<Parent>
 <Header/>
</Parent>

header 也是一个带有一些文本输入字段和图标的视图。 Parent 是通过添加 Header 组件创建的另一个视图。所以我想做的是,当我在 Header 视图中的文本字段中键入一些文本时,我想将该值传递给 Parent 视图道具。这该怎么做???我已经尝试了 Whosebug 中显示的一些答案。但是他们并没有给我我所期望的。

对于想要查看完整代码的人,这是 parent 屏幕。

export default class ParentScreen extends Component {
  constructor(props) {
    super(props);

    this.state = {
      objects: null,
      indicator: true,
    };
  }

render(){
 <View style={styles.container}>
       <HeaderBar />
    </View>
}}

这是 Header 屏幕。

export default class HeaderBar extends Component {
  constructor(props) {
    super(props);
  }
  state = {
    searchEnabled: false
  };

  render() {
    return (
      <View style={styles.navigationBar}>
        <View style={styles.titleArea}>
          {this.state.searchEnabled === true ? (
            <View style={styles.titleArea}>
              <Icon
                name="arrow-back"
                type="Ionicons"
                color="black"
                onPress={() => this.setState({ searchEnabled: false })}
              />
              <TextInput
                placeholder="Search"
                placeholderTextColor="white"
                style={styles.input}
                onChangeText={text => this.setState({ filterKey: text })}
              />
            </View>
          ) : (
            <View style={styles.titleArea}>
               <Image
                  style={styles.profileImage}
                  source={require("../../images/user_image_1.jpg")}
                />
            </View>
          )}
        </View>
      </View>
    );
  }
}

在parent视图中定义一个函数,类似于:

  onChangeText = (text) => {
    this.setState({
      myUpdatedText: text
    })
  }

然后,将其作为 prop 传递给 child:

  <HeaderBar onChangeText={this.onChangeText} />

所以在 child 代码中你可以像这样使用它:

  <TextInput
    placeholder="Search"
    placeholderTextColor="white"
    style={styles.input}
    onChangeText={this.props.onChangeText}
  />