[英]React native change state loop
我正在构建一个反应本机应用程序,其中一个post
有comments
。 我只是想显示comments
时,用户点击load comments...
。 问题是我如何处理每个帖子的状态(有多个帖子)。 我试过了,但它不起作用(renderPost 是一个循环):
const renderPost = ({ item, index}) => {
let fetchComments = false;
return (
<View style={[t.mB6]}>
<View style={[t.roundedLg, t.overflowHidden, t.shadow, t.bgWhite, t.hAuto]}>
<TouchableOpacity
key={item.id}
onPress={() => {
fetchComments = true;
}}>
<Text style={[t.fontBold, t.textBlack, t.mT2, t.mL4, t.w1_2]}>
load comments...
</Text>
</TouchableOpacity>
</View>
{ fetchComments ? <Comments postId={item.id}/> : null }
</View>
)
}
在上面的代码中,当用户单击load comments...
时,我将let fetchComments
设置为 true 。
renderPost 是一个功能组件,它没有自己的渲染和自己的状态,您可以通过其父 React.Component 中的 renderPost 道具传递一个更改状态的函数来解决这个问题。
例子:
//imports
class FatherComponentWithState extends React.component{
state={
fetchComments:false,
//(...OTHERSTUFFS)
}
setFetchComments = () =>{
this.setState({fetchComments:true})
}
render(){
return(
//(...FatherComponentStuffs)
{new renderPost({
setFetchComments: this.setFetchComments,
fetchComments:this.state.fetchComments,
//(...renderPostOtherStuffs like item, index)
})}
//(...FatherComponentStuffs)
)}}
renderPost 函数将接收它,如下所示:
const renderPost = (props) =>{
let fetchComments = props.fetchComments;
let setFetchComments = props.setFetchComments;
let item = props.item
let index = props.index
//...renderPost return remains the same
}
PS:如果你有多个 renderPost,你可以使用 fetchComments 作为一个布尔数组并将状态设置为 true 传递一个索引作为 setFetchComments 函数的参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.