反应原生道具到父组件

时间:2018-11-06 11:38:58

标签: reactjs react-native react-navigation

一开始,我很抱歉我是原生反应新手

我有一个带有反应导航的项目,其中显示了此组件。

import React, { Component } from 'react';
import {FlatList,StyleSheet,View,TouchableHighlight,Text} from 'react-native'
import {
  Container,
  Button,
  ListItem,
  Left,
  Right,
  Icon,
  Body
} from 'native-base';
import Customer from '../Customer';
import Search from '../../../components/Search'


export default class SearchCustomer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      customerList:[]
    }
  }



  render() {
    return (
      <Customer>
        <Search
          setCustomerList = {(customerList) => {this.setState({customerList})}}
        />
        <FlatList
            data={this.state.customerList}
            keyExtractor={item => item.id}
            renderItem={({ item, index}) => (
              <ListItem onPress={(item) => this.props.callback()}>
                <Left style={styles.left}>
                    <Text>{item.firstname} {item.lastname}</Text>
                    <Text style={styles.subtitle}>{item.email}</Text>
                </Left>
                <Right>
                  <Icon name='arrow-forward' />
                </Right>
              </ListItem>
        )}/>
      </Customer>
    )
  }
}

此组件在下面将其父对象称为

import React, { Component } from 'react';
import {
  Container,
  Button,
  Text,
} from 'native-base';
import Order from '../Order';

export default class Customer extends Component {
  constructor(props) {
    super(props);
    this.state = {

    }
  }

  render() {
    return (
      <Order>
        {this.props.children}
      </Order>
    )
  }
}

我想知道如何通过这种配置将数据从孩子发送到他的父母。

当前,我正试图在父母中抓到this.props.callback(),但我无法使用此callback={() => {console.log('Ok')}}

我有这个错误

error onPress call

有人可以解决吗?

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

使用某些类,您可以在父类中定义一个方法,然后将该函数作为道具传递给子类

export default class Customer extends Component {
  constructor(props) {
    super(props);
    this.state = {

    }
  }

  callback = (data) => { console.log(data) } 

  render() {
    return (
      <Order callback={this.callback}>
        {this.props.children}
      </Order>
    )
  }
}

然后从子级开始,您可以在回调中为父级提供数据。

export default class Order extends Component {
  constructor(props) {
    super(props);
    this.state = {

    }
  }


  render() {
    return (
      <TouchableOpacity onPress={() => this.props.callback('hi')}>
        <Text>Click Me!</Text>
      </TouchableOpacity >
    )
  }
}
相关问题