首页 > 解决方案 > 如何在反应原生中从子视图中获取道具

问题描述

我有这样的反应原生观点。

<Parent>
 <Header/>
</Parent>

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

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

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

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

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

这是标题屏幕。

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>
    );
  }
}

标签: react-nativereact-native-navigation

解决方案


在父视图中定义一个函数,例如:

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

然后,将其作为道具传递给孩子:

  <HeaderBar onChangeText={this.onChangeText} />

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

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

推荐阅读