您好,我在调用子组件中作为 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)} />
但是这会导致性能问题。
我怎样才能使这项工作?
经过一段时间的测试,我找到了这个解决方案:
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)} />
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句