gpt4 book ai didi

react-native - 使用参数作为 Prop 的 React Native 传递函数

转载 作者:行者123 更新时间:2023-12-03 14:14:53 32 4
gpt4 key购买 nike

从我所读到的最好的尝试和构建具有与“哑”渲染器一样多的组件的 react 应用程序。你有你的容器来获取数据并将其作为 Prop 传递给组件。

在您想要将需要除事件以外的参数的函数传递到链中之前,这很好用。

class MyClass extends Component {


_onItemPress (myId) {
// do something using myId
}

render () {

return <MyComponent myID={10} onPress={(myId) => this._onItemPress(myId)} />

}

}

如果我只是将它作为我的 onPress 处理程序传递给 MyComponent,它在调用时不会返回 myId。为了解决这个问题,我最终做了这样的事情。
export default ({myId, onPress) => {
const pressProxy = () => {
onPress(myId)
}

return (
<TouchableHighlight onPress={pressProxy}>
<Text>Click me to trigger function</Text>
</TouchableHighlight>
)
}

我这样做完全不正确吗?我希望能够有一个简单的组件,我可以将它重用于列表项,它的唯一功能是获取标题、onpress 函数并返回要在 ListViews renderRow 函数中使用的列表项。然而,许多 onPress 函数需要在 onPress 中使用变量。

有没有更好的办法?

最佳答案

正确的语法是这样的:

render () {
let myId = 10;
return <MyComponent myID={myId} onPress={() => this._onItemPress(myId)} />
}

另外,如果您打算使用 this里面 _onItemPress (例如调用 MyClass 中的其他方法),您需要像这样绑定(bind)范围:
render () {
let myId = 10;
return <MyComponent
myID={myId}
onPress={() => this._onItemPress(myId).bind(this)} />
}

...或者如果您愿意,也可以在构造函数中绑定(bind)它:
constructor(props) {
super(props);
this._onItemPress = this._onItemPress.bind(this);
}

关于react-native - 使用参数作为 Prop 的 React Native 传递函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40220038/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com