反应本机功能作为平板项目中的道具

时间:2019-04-19 17:39:12

标签: reactjs react-native react-native-flatlist

你好,我在调用子组件中作为prop传递的函数时遇到问题。我试图只用相关的代码行复制我的代码:

class Parent extends Component {
  constructor(props) {
    super(props)
    this.press = this.press.bind(this)
  }
  press(param) {
    console.log(param)
  }
  renderItem = ({item}) => (
    <Child item={item} press={this.press} />
  )

  render() {
    return (
      <FlatList renderItem={this.renderItem} />
    )
  }
}

class Child extends PureComponent {

  handlePress(param) {
    // do some stuff
    // call parent function
    this.props.press(param)
  }
  render() {
    const { id } = item
    return <Button onPress={() => this.handlePress(id)} />
  }
}

当按下按钮的那一刻什么也没发生时,我已经开始使用类似的东西了

<Child press={(param) => this.press(param)} />

但这会导致性能问题。

我该如何进行这项工作?

2 个答案:

答案 0 :(得分:0)

经过一段时间的测试,我得出了这个解决方案:

class Parent extends Component {
  press = (param) => {
    console.log(param)
  }

  renderItem = ({item}) => (
    <Child item={item} press={this.press} />
  )

  render() {
    return (
      <FlatList renderItem={this.renderItem} />
    )
  }
}

class Child extends Component {

  handlePress(param) {
    // do some stuff
    // call parent function
    this.props.press(param)
  }

  render() {
    const { id } = item
    return <Button onPress={() => this.handlePress(id)} />
  }
}

答案 1 :(得分:-1)

这可能是一个很好的解决方案:与其将引用从按钮传递给父类,不如将按钮从子类中移除,而使用TouchableOpacity。

import {
  TouchableOpacity,
  View,
} from 'react-native'
class Parent extends Component {
  constructor(props) {
    super(props)
  }
  press(param) {
    console.log(param)
  }
  renderItem = ({item}) => (
      <TouchableOpacity onPress={()=>{this.press(item.id)}}>

        <Child item={item} />

      </TouchableOpacity>

  )

  render() {
    return (
      <FlatList renderItem={this.renderItem} />
    )
  }
}

class Child extends PureComponent {

  render() {
    // just your view content
    const { id } = item
    return <View />
  }
}